【问题标题】:Binary Tree Transformation二叉树变换
【发布时间】:2015-01-07 11:17:42
【问题描述】:
        1                                 5 
    /       \                             |
   2         3            -->             2
 /  \       / \                         /   \
4    5     6   7                       1     4
                                       |
                                       3
                                     /   \
                                    6     7

假设你有一棵像左边一样的二叉树,并尝试将它转换为右边的。

它的作用是碰撞二叉树的“任何”单个叶节点——本例为“5”——这使得叶节点成为新的根节点。原始根节点(及其子节点)——本例中的“1”及其子节点——占用了当时的叶节点空间。

一般算法是什么?

感谢您的帮助。

【问题讨论】:

  • 一个tree rotation,也许?至少,它的一些修改形式。

标签: algorithm data-structures tree transformation


【解决方案1】:

这在很大程度上取决于支持二叉树的结构(例如,是否存储每个节点的父节点,等等)。假设你存储了节点的值和左右后代(最基本的信息),问题就简化为从当前根到将成为新根的节点的所有弧“反转”。我猜是这样的,在 Java 风格的伪代码中:

void rev(Node u, Node v) {
  // make v point back to u
  if (v.left == null) v.left = u;
  else v.right = u;
  // free edge from u to link up
  if (u.left == v) u.left = null;
  else u.right = null;
}

boolean reroot(Node root, Node parent, Node newRoot) { // assumes that newRoot is a leaf
  if (root != null)
    if (root == newRoot) {
      rev(root, parent);
      return true;
    } else {
      if (reroot(root.left, root) || reroot(root.right, root)) {
        rev(root, parent);
        return true;
      }
    }
  }
  return false;
}

不过,我没有测试上面的代码。

编辑:初始调用将是 reroot(currentRoot, null, newRoot);

【讨论】:

    【解决方案2】:

    我的想法:从一个节点开始,我们将它的父节点和另一个未探索的分支添加到新树中作为新分支,然后我们通过迭代原始树直到它的根递归地构建新树。

    python 风格的伪代码是这样的:

    NewTree=Node
    NoLongerChildNode=NULL
    while (Node!=root):
        NewTree.attach(Node.anotherchild(NoLongerChildNode))
        NewTree=NewTree.attach(Node.parent)
        NoLongerChildNode=Node
        Node=Node.parent
    NewTree.attach(Node.anotherchild(NoLongerChildNode))
    

    【讨论】:

      猜你喜欢
      • 2012-02-28
      • 1970-01-01
      • 2021-03-20
      • 1970-01-01
      • 1970-01-01
      • 2020-08-24
      • 1970-01-01
      • 1970-01-01
      • 2017-04-14
      相关资源
      最近更新 更多