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: /**
2: * Definition for binary tree
3: * public class TreeNode {
4: * int val;
5: * TreeNode left;
6: * TreeNode right;
7: * TreeNode(int x) { val = x; }
8: * }
9: */
10: public class Solution {
11: public boolean isBalanced(TreeNode root) {
12: if(root==null)
13: return true;
14: if(!isBalanced(root.left)||!isBalanced(root.right))
15: return false;
16: if(Math.abs(maxDepth(root.left)-maxDepth(root.right))<=1)
17: return true;
18: else
19: return false;
20: }
21: public int maxDepth(TreeNode root) {
22: if(root==null)
23: return 0;
24: if(root.left==null&&root.right==null)
25: return 1;
26: return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
27: }
28: }
Discussion:The subtrees are all balanced doesn't mean the parent tree is balance. Then still need to check the heights of the subtrees make sure they are differs no more than one.
没有评论:
发表评论