码迷,mamicode.com
首页 > 其他好文 > 详细

110. Balanced Binary Tree

时间:2016-05-18 12:11:28      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:

    /*
    * 110. Balanced Binary Tree
    * 2016-5-17 by Mingyang
    * This improved algorithm works by checking the height of each subtree as we recurse
    * down from the root. On each node, we recursively get the heights of the left and right
    * subtrees through the checkHeight method. If the subtree is balanced, then check-
    * Height will return the actual height of the subtree. If the subtree is not balanced, then
    * checkHeight will return -1. We will immediately break and return -1 from the current call.
    * 自己刚开始做的时候,在主函数里面吧后面两个条件一起写在一个语句里面了,殊不知base case里面并没有false的statement
    */
   /*
    *Wrong one:
    *return isBalanced(root.left)&&isBalanced(root.right)&&(Math.abs(depth(root.left)-depth(root.right))<=1);
    *太傻叉了这种写法,基本的递归都不会,base case都没写好,如何写递归?
    *以后写递归以前,一定要知道哪些基本case,都没有return false的情况,就会进入死循环。
    */
    public boolean isBalanced(TreeNode root) {
        if (root == null)
            return true;
        if (Math.abs(depth(root.left) - depth(root.right)) > 1)
            return false;
        return isBalanced(root.left) && isBalanced(root.right);
    }
    private int depth(TreeNode root) {
        if (root == null)
            return 0;
        return Math.max(depth(root.left), depth(root.right)) + 1;
    }

 

110. Balanced Binary Tree

标签:

原文地址:http://www.cnblogs.com/zmyvszk/p/5504683.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!