【问题标题】:Recursively assigning positions to node in binary search tree递归地为二叉搜索树中的节点分配位置
【发布时间】:2014-12-26 22:42:54
【问题描述】:

您好,我正在寻找一种将树的位置递归分配给 int 索引的方法,以便可以将位置处的节点的值放入数组中。

所需的树位置按级别顺序指定,其中根位置为 1 (i),i 的左子节点位于位置 2i,右子节点位于 2i + 1 - 类似于堆结构。 Null 子节点不会获得分配给他们的位置。

        1
       / \
      2   3
     /\   /\
    4  5 6  7
       ...

 [1, 2, 3, 4, 5, 6, 7. ...]

而树中最大的位置应该是数组的大小。我的输出需要添加空值作为“空格”来测试节点值。

private int largestPos
// first call: assignPositions(root, 1)
assignPositions(node cur, int pos) {
   parent = new node;
   if curpos > largestPos
      largestPos = curPos

   if cur == null
      parent.pos = pos
   else
     current.pos = pos

   parent = cur
   if cur.left != null
      pos = 2 * pos
      assignPositions(cur.left, pos)
   if cur.right != null
      pos = 2 * pos + 1
      assignPositions(cur.right, pos)
}

当我尝试打印我的数组时,我得到前两个值被正确分配,然后一大块没有值的空值(在树中确认)不在树中。

我希望这样做是为了找出在树中删除后我需要的最小数组大小。

更新广度优先搜索数组:

public Key[] breadthFirstTraversal() {

    @SuppressWarnings("unchecked")
    Key[] keysFinal = new Key[largestPos];

    List<Key> queue = new List<Key>();
    List<Key> keysList = new List<Key>();
    List<Integer> positions = new List<Integer>();

    if (!isEmpty()) {
        Node tempNode = root;
        KeyValuePair<Key, Value> tempKey = null;

        queue.add(tempNode);

        while (!queue.isEmpty()) {
            queue.reset();
            tempKey = queue.remove();
            keysList.add(tempKey);

            tempNode = findKey(tempKey.getKey(), root);

            // adds keys in order on level in list
            if (tempNode.getLeftChild() != null) {
                queue = addAtEnd(queue, tempNode.getLeftChild());
            }
            if (tempNode.getRightChild() != null) {
                queue = addAtEnd(queue, tempNode.getRightChild()); 
            }
        }

        for (int i = 1; i < largestPos + 1; i++) {
            keysList.reset();
            tempKey = keysList.remove();
            tempNode = findKey(, root);
            if (tempNode.getPosition() == i) {
                keysFinal[i - 1] = tempKey;
            } else {
                keysFinal[i - 1] = null;
            }
        }
    }

    return keysFinal;
}

【问题讨论】:

  • 处理树的正常递归方式在这里不起作用。我认为您要做的是在处理 1 级时,保留要处理的 2 级节点的“待办事项”列表。然后遍历这个列表,在处理它的同时,保留一个 3 级节点的“待办事项”列表。然后,当您完成第 2 级时,请查看第 3 级节点的列表等。或者您可以将所有内容放在一个队列中。在 Wikipedia 中查找“树遍历”并向下滚动到“广度优先搜索”。
  • @ajb 我添加了我当前的广度优先搜索。

标签: java recursion tree


【解决方案1】:

您正在更改 pos 以在左子树上工作,但随后希望原始值在右子树上工作。所以不要改pos,只要把你想要的表达式放在assignPositions的调用中即可。

再一次,您不断为您访问的每个节点创建新节点,但我没有看到任何数组,所以问题远不止这些。

【讨论】:

  • 数组稍后出现,我再次遍历树,查看当前节点的位置,然后从该位置将节点值添加到索引 [节点位置 - 1] 处的数组中。数组不是这个问题的必要部分,因为它被用作上面当前问题的结果。
  • 所以你的意思是在 if 语句 'if (left != null) { leftPos = 2 * pos; assignPositions(cur.left, leftPos;` 和 right 一样?
  • 或者你可以把表达式放在调用中;例如,assignPositions(cur.left, 2*pos)
猜你喜欢
  • 2012-01-26
  • 1970-01-01
  • 1970-01-01
  • 2018-03-19
  • 2014-05-10
  • 2013-03-10
  • 2014-01-02
  • 1970-01-01
  • 2017-10-30
相关资源
最近更新 更多