LeetCode Online Judge 题目C# 练习 - 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.
1 public static bool BalancedBinaryTree(BTNode root) 2 { 3 if (root == null) 4 return true; 5 6 if(Math.Abs(GetDepth(root.Left) - GetDepth(root.Right)) >= 2) 7 return false; 8 else 9 return BalancedBinaryTree(root.Left) && BalancedBinaryTree(root.Right); 10 } 11 12 public static int GetDepth(BTNode root) 13 { 14 if (root == null) 15 return 0; 16 if (root.Left == null && root.Right == null) 17 return 1; 18 else 19 return 1 + Math.Max(GetDepth(root.Left), GetDepth(root.Right)); 20
代码分析:
看来是永无止境了,LeetCode上加了些Tree的题目,在做些吧,反正自己递归很弱。
上面是递归Top-down的做法,不知有没有bottom-up的做法,DP之类的。