Leetcode 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.

 

 1 public class Solution {
 2     // note: height balanced tree is not necessary a complete tree or full tree, but a complete/full tree is always hight balanced
 3     public bool IsBalanced(TreeNode root) {
 4         return GetMaxDepth(root) != -1;
 5     }
 6     
 7     // it return -1 if it's not balanced
 8     private int GetMaxDepth(TreeNode node)
 9     {
10         if (node == null) return 0;
11         var l = GetMaxDepth(node.left);
12         if (l != -1)
13         {
14             var r = GetMaxDepth(node.right);
15             if (r != -1)
16             {
17                 return l - r <= 1 && l - r >= -1 ? Math.Max(l, r) + 1 : -1;
18             }
19         }
20         
21         return -1;
22     }
23 }

 

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left;
 6  *     public TreeNode right;
 7  *     public TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     // note: height balanced tree is not necessary a complete tree or full tree, but a complete/full tree is always hight balanced
12     private Dictionary<TreeNode, int> cache = new Dictionary<TreeNode, int>();
13     public bool IsBalanced(TreeNode root) {
14         if (root == null) return true;
15         
16         var l = GetMaxDepth(root.left);
17         var r = GetMaxDepth(root.right);
18         
19         if (l - r <= 1 && l - r >= -1) return IsBalanced(root.left) && IsBalanced(root.right);
20         return false;
21     }
22     
23     private int GetMaxDepth(TreeNode node)
24     {
25         if (node == null) return 0;
26         if (cache.ContainsKey(node)) return cache[node];
27         
28         var h = Math.Max(GetMaxDepth(node.left) + 1, GetMaxDepth(node.right) + 1);
29         cache[node] = h;
30         return h;
31     }
32 }
33 
34 public class Solution1 {
35     public bool IsBalanced(TreeNode root) {
36         if (root == null) return true;
37         
38         var l = GetMaxDepth(root.left, 0);
39         var r = GetMaxDepth(root.right, 0);
40         
41         if (l - r <= 1 && l - r >= -1) return IsBalanced(root.left) && IsBalanced(root.right);
42         return false;
43     }
44     
45     // note: I tried to cache the node/depth to save time, but it didn't work. As the depth of the node is the max depth from the original     // parent node.
46     private int GetMaxDepth(TreeNode node, int cur)
47     {
48         if (node == null) return cur;
49         
50         return Math.Max(GetMaxDepth(node.left, cur + 1), GetMaxDepth(node.right, cur + 1));
51     }
52 }

 

posted @ 2017-11-18 03:34  逸朵  阅读(141)  评论(0)    收藏  举报