美文网首页
平衡二叉树

平衡二叉树

作者: Crazy_Bear | 来源:发表于2020-07-28 09:33 被阅读0次
    • 输入一棵二叉树,判断该二叉树是否是平衡二叉树。

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

    • 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);
         }    
    };
    

    相关文章

      网友评论

          本文标题:平衡二叉树

          本文链接:https://www.haomeiwen.com/subject/cxrjlktx.html