美文网首页
110. Balanced Binary Tree

110. Balanced Binary Tree

作者: namelessEcho | 来源:发表于2017-10-01 21:35 被阅读0次

    可以在调用链回归时进行比较以避免重复计算深度。

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        boolean balanced=true;
        public boolean isBalanced(TreeNode root) {
                balanceHelper(root);
                return balanced;
        }
        private int balanceHelper(TreeNode root)
        {
            if(root==null) return 0;
            int right =  balanceHelper(root.right);
            int left =   balanceHelper(root.left);
            if(Math.abs(right-left)>1)
                balanced=false;
            return left>right?left+1:right+1;
    
        }
    }
    

    相关文章

      网友评论

          本文标题: 110. Balanced Binary Tree

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