【问题标题】:Convert the structure of the tree like a left aligned tree whose each node contains a down pointer and a right pointer将树的结构转换为左对齐树,其每个节点都包含一个下指针和一个右指针
【发布时间】:2015-02-27 12:35:57
【问题描述】:

这是在接受亚马逊采访时提出的问题。 给定如下二叉树

                  A
                 / \
                B   C
                   /  \
                   D   E
                  /   / \
                 F   G   H 

将树的结构转换为左对齐树,其每个节点都包含一个向下指针和一个右指针,看起来像下面的树。

        A
        |
        B – C
        |
        D—E
        |
        F—G – H

谁能帮我解决这个问题。 谢谢。

【问题讨论】:

  • 你试过了吗?看起来,对于每个最左边(和根)节点,您正在创建一个向下指针,该指针指向下一层的最左边节点,以及一个链接到具有同一级别的所有节点的列表的右指针

标签: algorithm data-structures tree binary-tree


【解决方案1】:

您可以使用修改后的breadth first search 来执行此操作。您需要使用边界跟踪何时切换到新级别。

这样的事情应该可以工作。

Queue queue = new queue();
Queue frontier = new queue(); 
queue.enqeue(root.children);
newTree.add(root);
previousLevelParent = root;
addRightPointer = false;
while (!queue.isEmpty())
    Node tmp = queue.dequeue();
    frontier.enqueue(tmp.children);
    if (addRightPointer)
        //Add this to the right of current level
        newTree.addRight(tmp);
    else 
       //Create new level in the new tree with the
       //previousLevelParent as the parent
       newTree.createNewLevel(previousLevelParent, tmp);
       previousLevelParent = tmp;
       addRightPointer = true;
    if (queue.isEmpty())
        queue = frontier;
        frontier = new queue();
        addRightPointer = false;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 2011-04-15
    • 2023-03-16
    • 2016-04-29
    • 2016-03-01
    相关资源
    最近更新 更多