LeetCode:Maximum Depth of Binary Tree_104

LeetCode:Maximum Depth of Binary Tree

【问题再现】

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

【优质算法】

算法一:

  public class Solution {
      public int maxDepth(TreeNode root) {
          if(root==null)
              return 0;
        
          int Left = maxDepth(root.left)+1;
          int Right = maxDepth(root.right)+1;
        
          if(Left>Right)
              return Left;
          else
              return Right;
    }
}

算法二:

    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
    }

【题后反思】

  这道题看似很难,看了答案没想到如此的简单。使用深度优先算法是大材小用,因为我们仅仅是要一个数字结果。

  这道题的递归思想也是很简单的,但是我没有直接答出来...弱鸡

  递归思想分析(以算法一为线索,个人愚见):

   (图片转载自网络)

   【递归都要给一个root节点,如一图中的10号节点。这时候我们要分两路,分别判断每一路的最大深度】。其实递归的就是【】内的内容。二叉树中每个节点都是root节点,(递)最后root节点便分解到页节点的空子节点,然后我们要(归),空子节点当然要返回0了,然后到了子树的分叉口时,我们要判断从分叉口这里分出区的到底那个最大,然后返回最大的。然后归的过程中不但重复判断,最后便得到了最大深度。

  

     

 

原文地址:https://www.cnblogs.com/MrSaver/p/5907469.html