我目前正在实现二进制搜索树 . 我的教材说明树的深度等于最深叶的深度 . 节点本身的深度定义为从根到该节点的边缘量 . 但是当我想在互联网上检查我的实现是否正确时,我发现很多实现都是这样的:
int Tree::Depth()
{
if (!this)
{
return 0;
}
return max(this->left.Depth(), this->right.Depth()) + 1;
}
-
http://codercareer.blogspot.be/2013/01/no-35-depth-of-binary-trees.html
-
What's the difference between these two code for find the max depth of a binary tree?
但是使用 return 0
给出节点数量而不是边缘量(节点数量=边缘数量1) . 不应该是 return -1
? Robert Sedgewick似乎也使用了-1:
/**
* Returns the height of the BST (for debugging).
*
* @return the height of the BST (a 1-node tree has height 0)
*/
public int height() {
return height(root);
}
private int height(Node x) {
if (x == null) return -1;
return 1 + Math.max(height(x.left), height(x.right));
}
定义 . 树的大小是其节点数 . 树中节点的深度是从它到根的路径上的链接数 . 树的高度是其节点之间的最大深度 .
〜算法(第4版)由罗伯特塞奇威克和凯文韦恩
在“算法简介”第3页的第490页可以看到深度为0的根的示例 . 由Thomas H. Cormen,Charles E. Leiserson,Ronald L. Rivest和Clifford Stein编辑 .
有人能帮助我清除混乱吗?