Balanced Binary Tree

来源:互联网 发布:手机文档解密软件 编辑:程序博客网 时间:2024/06/07 00:29

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则不是平衡二叉树,如果小于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 boolean isBalanced(TreeNode root) {        if(root==null) return true;        int left=sub_height(root.left);        int right=sub_height(root.right);        int diff=Math.abs(left-right);        if(diff>1) return false;        else return  isBalanced(root.left) && isBalanced(root.right);    }    public int sub_height(TreeNode subTree)    {        if(subTree==null) return 0;        if(subTree.left==null && subTree.right==null) return 1;        if(subTree.left==null) return sub_height(subTree.right)+1;        if(subTree.right==null) return sub_height(subTree.left)+1;        return Math.max(sub_height(subTree.right),sub_height(subTree.left))+1;    }}



0 0