【问题标题】:Assign in-order index to Binary Tree将有序索引分配给二叉树
【发布时间】:2018-03-07 02:20:05
【问题描述】:

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

给定下面的一棵树:

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

【问题讨论】:

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


    【解决方案1】:

    上述程序的问题是在两个不同的场合返回两个不同的值。因此,如果您不想使用全局变量,则可以通过在所有情况下仅返回最新的索引值来解决此问题。

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

    【讨论】:

      猜你喜欢
      • 2017-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      相关资源
      最近更新 更多