您的位置:首页 > 编程语言 > Java开发

LeetCode|Balanced Binary Tree-java

2015-09-26 16:27 561 查看
题目:

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.

思路:

判断一个二叉树是不是平衡二叉树(如果树所有节点的左子树和右子树的高度差不超过1就是平衡二叉树),这也是典型的递归算法题。对左右子树的高度作比较,然后递归分别对左右子树的孩子的高度继续做比较。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
   public static int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);

        return leftDepth > rightDepth ? (leftDepth + 1) : (rightDepth + 1);
    }

    public static boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        int diff = Math.abs(maxDepth(root.left) - maxDepth(root.right));
        return diff <= 1 && isBalanced(root.left) && isBalanced(root.right);
    }
}


如果我们用后序遍历的方式遍历一遍二叉树的每一个节点,在遍历到一个节点之前我们就已经遍历了它的左右子树。只要在遍历每个节点的时候记录它的深度(某一节点的深度等于它到节点的路径的长度),我们一遍遍历一遍判断每个节点是不是平衡的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: