93 · Balanced Binary Tree
Algorithms
Easy
Accepted Rate
44%
Description
Solution
Notes
Discuss
Leaderboard
Record
Description
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 depth of the two subtrees of every node never differ by more than 1.
Wechat reply 【Google】 get the latest requent Interview questions. (wechat id : jiuzhang0607)
Example
Example 1:
Input:
tree = {1,2,3}
Output:
true
Explanation:
This is a balanced binary tree.
1
/ \
2 3
Example 2:
Input:
tree = {1,#,2,3,4}
Output:
false
Explanation:
This is not a balanced tree.
The height of node 1’s right sub-tree is 2 but left sub-tree is 0.
1
\
2
/ \
3 4
Tags
Related Problems
95
Validate Binary Search Tree
Medium
467
Complete Binary Tree
Easy
解法1:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
struct RetType {
int height;
bool balanced;
RetType(int h = 0, bool b = true) : height(h), balanced(b) {}
};
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
bool isBalanced(TreeNode *root) {
RetType res = helper(root);
return res.balanced;
}
private:
RetType helper(TreeNode *root) {
if (!root) return RetType(0, true);
if (!root->left && !root->right) return RetType(1, true);
RetType leftRet = helper(root->left);
if (!leftRet.balanced) return RetType(0, false);
RetType rightRet = helper(root->right);
if (!rightRet.balanced) return RetType(0, false);
if (abs(leftRet.height - rightRet.height) > 1) {
return RetType(0, false);
} else {
return RetType(max(leftRet.height, rightRet.height) + 1, true);
}
}
};
二刷:用后序遍历。如果递归函数里面又用到其它递归函数,那么时间复杂度很高,可以考虑后序遍历。
class Solution {
public:
bool isBalanced(TreeNode* root) {
depth(root);
return balanced;
}
private:
bool balanced = true;
int depth(TreeNode *root) {
if (!balanced || !root) return 0; //如果已经!isBalanced,也没有必要继续了。
int left = depth(root->left);
int right = depth(root->right);
if (abs(left - right) > 1) balanced = false;
return max(left, right) + 1;
}
};