首页 > 代码库 > 110. Balanced Binary Tree

110. Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Solution 1:

思路:首先判断root.left和root.right是否有符合条件的depth,加入辅助函数,也就是104的maxdepth,然后再递归检查左子树和右子树。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public boolean isBalanced(TreeNode root) {        if(root==null)        {            return true;        }        if(Math.abs(depth(root.left)-depth(root.right))<=1)        {            return isBalanced(root.left)&&isBalanced(root.right);        }        else        {            return false;        }    }            public int depth(TreeNode root)    {        if(root==null)        {            return 0;        }        return Math.max(depth(root.left),depth(root.right))+1;    }            }

Solution 2: 

discussion看到一种更巧妙的做法:

public boolean isBalanced(TreeNode root) {    return getDepth(root) != -1;}private int getDepth(TreeNode root) {    if (root != null) {        int left = getDepth(root.left);        int right = getDepth(root.right);                return (left == -1 || right == -1 || Math.abs(left-right) > 1) ? -1 : Math.max(left, right) + 1;    }        return 0;}

Define a getDepth method, which will return the height of the tree, if it is balanced, otherwise, return -1.

定义的这个getDepth行使两个功能,一是记录depth如果balanced,二是记录-1如果不balanced。

定义好一个recursion的函数很重要啊!!

110. Balanced Binary Tree