【面试题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         }

 

转载于:https://www.cnblogs.com/HuoAA/p/4830919.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值