【面试题39】二叉树的深度

【题目描述】

输入一棵二叉树的根结点,求该树的深度。

【解决方案】

递归解决。

我的代码实现,仅供参考:

 1         public static int TreeDepth(TreeNode root)
 2         {
 3             if (root == null)
 4                 return 0;
 5             
 6             int leftDepth = TreeDepth(root.left);
 7             int rightDepth = TreeDepth(root.right);
 8 
 9             return leftDepth > rightDepth ? (leftDepth + 1) : (rightDepth + 1);
10         }

【本题扩展】

输入一棵二叉树的根结点,判断该树是不是平衡二叉树。

解法一:需要重复遍历结点多次的解法,简单但不足以打动面试官

我的代码实现,仅供参考:

 1         public static bool IsBalanced(TreeNode root)
 2         {
 3             if (root == null)
 4                 return true;
 5 
 6             int leftDepth = TreeDepth(root.left);
 7             int rightDepth = TreeDepth(root.right);
 8 
 9             if (Math.Abs(leftDepth - rightDepth) > 1)
10                 return false;
11 
12             return IsBalanced(root.left) && IsBalanced(root.right);
13         }
14 
15         public static int TreeDepth(TreeNode root)
16         {
17             if (root == null)
18                 return 0;
19             
20             int leftDepth = TreeDepth(root.left);
21             int rightDepth = TreeDepth(root.right);
22 
23             return leftDepth > rightDepth ? (leftDepth + 1) : (rightDepth + 1);
24         }

解法二:每个结点只遍历一次,正式面试官喜欢的

我的代码实现,仅供参考:

 1         public static bool IsBalanced(BinaryTreeNode root)
 2         {
 3             int depth = 0;
 4 
 5             return IsBalanced(root, ref depth);
 6         }
 7 
 8         public static bool IsBalanced(BinaryTreeNode root, ref int depth)
 9         {
10             if (root == null)
11                 return true;
12 
13             int left = 0, right = 0;
14 
15             if (IsBalanced(root.Left, ref left) && IsBalanced(root.Right, ref right))
16             {
17                 if (Math.Abs(left - right) <= 1)
18                 {
19                     depth = 1 + (left>right? left :right);
20                     return true;
21                 }
22             }
23 
24             return false;
25         }

 

posted @ 2015-09-22 23:36  叫我霍啊啊啊  阅读(179)  评论(0编辑  收藏  举报