int count(Node node) {
if (node == null)
return 0;
int r = count (node.right);
int l = count (node.left);
return 1 + r + l;
}
此函数返回以节点为根的二叉树中的节点数。有几篇文章说这是前序遍历,但对我来说这看起来像是后序遍历,因为我们在访问根之前先访问左侧和右侧部分。我在这里错了吗?还是我的“访问”概念有误?
最佳答案
在此代码中,每个节点都没有进行实际处理,因此前序遍历和后序遍历之间没有区别。如果有处理,区别将是:
预购
int count(Node node) {
if (node == null)
return 0;
process(node);
int r = count (node.right);
int l = count (node.left);
return 1 + r + l;
}
后订单
int count(Node node) {
if (node == null)
return 0;
int r = count (node.right);
int l = count (node.left);
process(node);
return 1 + r + l;
}
(实际上,在这些情况下——与您的代码不同——您可能希望在 node.right
之前递归 node.left
以保留传统的左-处理子项的右排序。)
关于java - 这个程序怎么是先序遍历呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25713404/