将顺序索引分配给二叉树

时间:2018-03-07 02:20:05

标签: algorithm data-structures binary-tree array-algorithms

我们如何为二叉树分配有序索引?

给出下面的树:

      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;
    }

1 个答案:

答案 0 :(得分:2)

上述程序中的问题是在两个不同的场合返回两个不同的值。因此,如果您不想使用全局变量,只需返回最新的索引值即可解决问题。

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;

}
相关问题