平衡二叉树
2020-07-28 本文已影响0人
Crazy_Bear
- 输入一棵二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
- Java 代码
public class Solution {
boolean res = true;
public boolean IsBalanced_Solution(TreeNode root) {
height(root);
return res;
}
public int height(TreeNode root){
if(root == null) return 0;
int left = height(root.left);
int right = height(root.right);
if(Math.abs(right - left) > 1) res = false;
return 1 + Math.max(right,left);
}
}
- C++ 代码
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(!pRoot) return true;
bool res = true;
isBalanced(pRoot, res);
return res;
}
int isBalanced(TreeNode *pRoot, bool &res){
if(!pRoot) return 0;
int left = isBalanced(pRoot->left, res);
int right = isBalanced(pRoot->right, res);
if(abs(left -right)>1) res = false;
return 1+(left>right?left:right);
}
};