题目描述
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.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
题目思路
- 剑指offer 273
代码 C++
- 思路一、需要重复遍历节点多次的解法
如果每个节点的左右子树的深度相差都不超过1,那么按照定义它就是一颗平衡二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(root == NULL){
return true;
}
int depth_left = Depth(root->left);
int depth_right = Depth(root->right);
int tt = depth_left - depth_right;
if(tt < -1 || tt > 1){
return false;
}
return isBalanced(root->left) && isBalanced(root->right);
}
int Depth(TreeNode* root){
if(root == NULL){
return 0;
}
int depth_left = Depth(root->left);
int depth_right = Depth(root->right);
return (depth_left > depth_right) ? (depth_left+1) : (depth_right+1);
}
};
- 思路二、每个节点只遍历一次的解法,正是面试官喜欢的
在下面代码中,我们用后序遍历的方式遍历整颗二叉树。
在遍历某节点的左右子节点之后,我们可以根据它的左右子节点的深度判断它是不是平衡的,并得到当前结点的深度。当最后遍历到树的根节点的时候,也就判断了整颗二叉树是不是平衡二叉树。
class Solution {
public:
bool isBalanced(TreeNode* root) {
int depth = 0;
return core(root, &depth);
}
bool core(TreeNode* root, int* depth){
if(root == NULL){
*depth = 0;
return true;
}
int left, right;
if(core(root->left, &left) && core(root->right, &right)){
int diff = left - right;
if(diff >= -1 && diff <= 1){
*depth = (left > right) ? left+1 : right+1;
return true;
}
}
return false;
}
};