zoukankan      html  css  js  c++  java
  • 【面试题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         }
  • 相关阅读:
    企业如何在智能制造的时代保持竞争力?
    汽车行业MES系统在产品追溯方面的应用分析
    你能想象未来的MES系统是什么样吗?
    智能制造进入下半场?APS如何进行优化
    【案例】如何让阀门制造提高排产效率?APS系统帮你实现
    APS系统的现状以及与MES系统的关联
    MES被重新定义?做到这几点才算智能制造
    python部分笔记
    BUUCTF Hack World
    BUUCTF--checkin
  • 原文地址:https://www.cnblogs.com/HuoAA/p/4830919.html
Copyright © 2011-2022 走看看