[LeetCode] Height of Special Binary Tree

2773. Height of Special Binary Tree

You are given a root``n nodes. The nodes of the special binary tree are numbered from 1 to n. Suppose the tree has k leaves in the following order: b1 < b2 < ... < bk.

bi, the following conditions hold:

  • The right child of bi is bi + 1 if i < k, and b1 otherwise.
  • The left child of bi is bi - 1 if i > 1, and bk otherwise.

Return the height of the given tree.

Note: The height of a binary tree is the length of the longest path from the root to any other node.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
unordered_map<int, int> freq;

void dfs1(TreeNode* u) {
if(++freq[u->val] > 3) return;
if(u->left) dfs1(u->left);
if(u->right) dfs1(u->right);
}
void dfs2(TreeNode* u, int& res, int dep = 0) {
res = max(res, dep);
if(freq[u->val] == 1) {
if(u->left) dfs2(u->left,res,dep+1);
if(u->right) dfs2(u->right,res,dep+1);
}
}
public:
int heightOfTree(TreeNode* root) {
freq = {};
int res = 0;
dfs1(root);
dfs2(root,res);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/08/11/PS/LeetCode/height-of-special-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.