平衡二叉树

2020-07-28  本文已影响0人  Crazy_Bear

在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树

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);
    }
}
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);
     }    
};
上一篇下一篇

猜你喜欢

热点阅读