LeetCode - 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 everynode 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 int Depth(TreeNode root){

12         if(root == null)

13             return 0;

14         return 1 + Math.max(Depth(root.left), Depth(root.right));

15     }

16     public boolean isBalanced(TreeNode root) {

17         // Start typing your Java solution below

18         // DO NOT write main() function

19         if(root == null) return true;

20         int leftDepth = Depth(root.left);

21         int rightDepth = Depth(root.right);

22         if(Math.abs(leftDepth - rightDepth) > 1)

23             return false;

24         else

25             return isBalanced(root.left) && isBalanced(root.right);

26     }

27 }

 

你可能感兴趣的:(LeetCode)