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


当前回答

根据Cormen等人。算法简介(附录B.5.3),树T中节点X的深度定义为从T的根节点到X的简单路径的长度(边数),节点Y的高度是从Y到叶子的最长的向下简单路径上的边数。树的高度定义为其根节点的高度。

注意,简单路径是没有重复顶点的路径。

树的高度等于树的最大深度。节点的深度和高度不一定相等。这些概念的说明见Cormen et al.第三版的图B.6。

我有时会遇到要求计算节点(顶点)而不是边的问题,所以如果你不确定是否应该在考试或工作面试中计算节点或边,就要求澄清。

其他回答

我想写这篇文章是因为我是一名计算机专业的本科生,我们越来越多地使用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.

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

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

树的属性:

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

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

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

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

根据Cormen等人。算法简介(附录B.5.3),树T中节点X的深度定义为从T的根节点到X的简单路径的长度(边数),节点Y的高度是从Y到叶子的最长的向下简单路径上的边数。树的高度定义为其根节点的高度。

注意,简单路径是没有重复顶点的路径。

树的高度等于树的最大深度。节点的深度和高度不一定相等。这些概念的说明见Cormen et al.第三版的图B.6。

我有时会遇到要求计算节点(顶点)而不是边的问题,所以如果你不确定是否应该在考试或工作面试中计算节点或边,就要求澄清。