如何为二叉树分配顺序索引?
下面有一棵树:
1
2 3
4 5 6 7将下面的索引分配给上面的树,如下所示:
4
2 6
1 3 5 7下面的代码不适用于第6种情况,因为它分配了10,因为我们是在重复计算,从参数和左子节点传递索引。我们能在不使用全局变量的情况下实现这一点吗?
int assignIndex(Node root, int index) {
if (root == null)
return 0;
int leftIndex = assignIndex(root.left, index);
root.index = leftIndex + index + 1;
int rightIndex = assignIndex(root.right, root.index);
if (rightIndex == 0)
return root.index;
else
return rightIndex;
}发布于 2018-03-07 03:30:50
上述程序的问题是在两个不同的场合返回两个不同的值。因此,如果您不想使用全局变量,可以通过在所有情况下只返回最新的索引值来解决这个问题。
int assignIndex(Node root, int index) {
if (root.left != null)
index = assignIndex(root.left, index);
index++;
root.index = index;
if (root.right != null)
index = assignIndex(root.right, index);
return index;
}https://stackoverflow.com/questions/49143077
复制相似问题