leetcode(30).110. Balanced Binary Tree

来源:互联网 发布:java哈希表 编辑:程序博客网 时间:2024/06/06 05:30

题意:判断给定的二叉树是否是平衡树。(平衡树是指树的子树结点高度差不超过一)

初步分析:

深度考虑深度优先搜索,采用递归的方式实现。再比较判断高度差是否超过1.

我们可以把递归的部分设置为高度

然后,现在我们可以获得子树的高度了,那么左子树和右子树的高度差不能超过1。

然而,仅仅这样是错的。

比如

         *

      *     *

   *         *

 *

根节点的左子树和右子树虽然只差了1.,但是对于左子树

     *

  *

*

显然是不平衡的。

所以,判断平衡也是递归的,不仅自己要平衡,还要递归的判断左子树和右子树也是平衡的。

public class Solution {    public boolean isBalanced(TreeNode root) {        if (root == null)               return true;        return (Math.abs(getHeight(root.left) - getHeight(root.right)) < 2)                   && isBalanced(root.left)                  && isBalanced(root.right);    }        public int getHeight(TreeNode root) {          if (root == null)            return 0;        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));    }}

把非递归判断和递归分开也不无不可

public class Solution {    public boolean isBalanced(TreeNode root) {        if (root == null)               return true;        if(Math.abs(getHeight(root.left) - getHeight(root.right)) > 1)            return false;        return isBalanced(root.left) && isBalanced(root.right);    }        public int getHeight(TreeNode root) {          if (root == null)            return 0;        return 1 + Math.max(getHeight(root.left), getHeight(root.right));    }}


0 0
原创粉丝点击