简体   繁体   English

需要帮助来了解二叉树的最大深度[Leetcode]

[英]Need help understanding Maximum Depth of Binary Tree [Leetcode]

For the following: 对于以下内容:

var maxDepth = function(root) {
if(!root){
  return 0
}
var leftMax=maxDepth(root.left)
var rightMax=maxDepth(root.right)
return Math.max(leftMax, rightMax)+1};

I don't understand how the variables leftMax and rightMax work in conjunction with Math.max. 我不明白变量leftMax和rightMax如何与Math.max结合使用。 How is the variables numbers? 变量编号如何?

For example, lets say the tree looks like this: 例如,假设树看起来像这样:

     a
   /   
  b
 /
c

So first, it would reach here: var leftMax=maxDepth(root.left), root.left being b. 所以首先,它将到达此处:var leftMax = maxDepth(root.left),root.left为b。 What is leftMax at this point? 此时剩下的还有什么? Is it some number and where is the number from? 是一些数字,数字从哪里来?

Thanks 谢谢

Maximum depth of a binary tree can be presented as a maximum depth of its subtrees from left or right child plus 1 for the current level. 二叉树的最大深度可以表示为其子树从左或右子级开始的最大深度加当前级别的1。 Let the depth of a subtree be 0 if it's empty (no left or right child). 如果子树的深度为空(无左子或右子),则使子树的深度为0。

The depth of those subtrees, in turn, can be calculated in the same way. 这些子树的深度又可以用相同的方法计算。

var leftMax=maxDepth(root.left)
var rightMax=maxDepth(root.right)

So the algorithm divides subtrees until a leaf is reached. 因此,该算法将子树划分成一片叶子。 Leaves have no children (equivalent to "each child has zero depth"), so its maximum depth of subtrees is zero. 叶子没有子代(相当于“每个子代的深度为零”),因此其子树的最大深度为零。

if(!root){  // no child for the parent node
  return 0
}

Now let's add 1 for the current level and get back to the previous call. 现在让我们为当前级别添加1并返回到上一个调用。 The same operations for both left and right subtrees are performed, so the algorithm knows about the depth of right and left subtrees at the end of each iteration: 左右子树都执行相同的操作,因此算法在每次迭代结束时都知道左右子树的深度:

var leftMax=maxDepth(root.left)
var rightMax=maxDepth(root.right)

This means the current tree has a depth of max(subtrees depth) plus 1 for the current level: 这意味着当前树的深度为max(子树深度),当前层的深度为1:

return Math.max(leftMax, rightMax)+1};

In your example, the algorithm goes as deep as it can on the left children first and returns to visit righter ones. 在您的示例中,该算法首先在左侧的子级上尽可能深入,然后返回访问右侧的子级。 This strategy is called Depth-first search 此策略称为深度优先搜索

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM