[LeetCode] Balanced Binary Tree

110. Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as:

a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

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
/**
* 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 {
bool res = true;
int travel(TreeNode* node, int lvl) {
if(!node) return lvl-1;
auto llvl = travel(node->left, lvl + 1);
auto rlvl = travel(node->right, lvl + 1);
int milvl = min(llvl, rlvl), malvl = max(llvl, rlvl);
if(malvl - milvl > 1) res = false;
return malvl;
}
public:
bool isBalanced(TreeNode* root) {
travel(root, 0);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/22/PS/LeetCode/balanced-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.