这是算法理论中的一个简单问题。 它们之间的区别是,在一种情况下,你计算节点的数量,在另一种情况下,计算根节点和具体节点之间最短路径上的边的数量。 哪个是哪个?


当前回答

我知道这很奇怪,但是Leetcode也根据路径上的节点数量来定义深度。因此,在这种情况下,深度应该从1开始(总是计算根),而不是0。以防有人和我一样有同样的困惑。

其他回答

Daniel A.A. pelsmaker的回答和Yesh的类比非常棒。我想从hackerrank教程中添加更多。希望这也能有所帮助。

节点的深度(或层次)是它的距离(即。从树的根节点开始。 高度是根节点和最远叶之间的边数。 height(node) = 1 + max(height(node. leftsubtree),height(node. rightsubtree)))。 在阅读下面的示例之前,请记住以下几点。 任何节点的高度都是1。 空子树的高度是-1。 单元素树或叶节点的高度为0。

我想写这篇文章是因为我是一名计算机专业的本科生,我们越来越多地使用OpenDSA和其他开源教科书。从评分最高的答案来看,似乎教高度和深度的方式一代一代都在改变,我把这篇文章贴出来是为了让每个人都意识到这种差异现在是存在的,希望不会在任何程序中导致错误!谢谢。

摘自OpenDSA数据结构和算法书:

If n1, n2,...,nk is a sequence of nodes in the tree such that ni is the parent of ni+1 for 1<=i<k, then this sequence is called a path from n1 to nk. The length of the path is k−1. If there is a path from node R to node M, then R is an ancestor of M, and M is a descendant of R. Thus, all nodes in the tree are descendants of the root of the tree, while the root is the ancestor of all nodes. The depth of a node M in the tree is the length of the path from the root of the tree to M. The height of a tree is one more than the depth of the deepest node in the tree. All nodes of depth d are at level d in the tree. The root is the only node at level 0, and its depth is 0. Figure 7.2.1: A binary tree. Node A is the root. Nodes B and C are A's children. Nodes B and D together form a subtree. Node B has two children: Its left child is the empty tree and its right child is D. Nodes A, C, and E are ancestors of G. Nodes D, E, and F make up level 2 of the tree; node A is at level 0. The edges from A to C to E to G form a path of length 3. Nodes D, G, H, and I are leaves. Nodes A, B, C, E, and F are internal nodes. The depth of I is 3. The height of this tree is 4.

简单的回答是: 深度: 1. 树:从树的根节点到叶节点的边/弧的数量称为树的深度。 2. 节点:从根节点到该节点的边数/弧数称为该节点的深度。

深度:节点上面有多少条边,这就是节点的深度 高度:节点下面有多少条边,即节点的高度

 Node1 // depth = 0 and height = 2 => root node
  |
 / \
Node2 Node3 //depth = 1 and height = 1
|     |
Node4 Node5  //depth = 2 and height = 0  => leaf node```

我了解到深度和高度是节点的属性:

节点深度是指从该节点到树的根节点的边数。根节点的深度为0。 节点的高度是指从该节点到叶节点的最长路径上的边数。叶节点的高度为0。

树的属性:

树的高度是它的根节点的高度,或者等价地,是它最深节点的深度。 树的直径(或宽度)是任意两个叶节点之间的最长路径上的节点数。下面的树直径为6个节点。