将每个叶节点的右指针更改为二叉树中的下一个叶节点

时间:2013-11-25 11:09:07

标签: algorithm binary-tree nodes tree-traversal

最近我在互联网上看到了一个问题,并想知道是否有比我所做的更有效的解决方案。

Queus:将每个叶节点的右指针更改为二叉树中的下一个叶节点。
叶子可能不在同一水平。

二叉树的节点具有以下形式:

struct node  
{  
     struct node *left , *right ;  
     int key;  
};

我在树上使用LEVEL ORDER TAVERSAL(BFS)解决了它,最后得到了队列中的所有叶子节点。
现在连接节点非常简单:

while(queue is not empty)  
{
  currentnode = queue.pop();
 currentnode->right= queue.top();
}
 currentnode->right= NULL;// queue becomes empty on taking out last node

我使用O(n)时间,但是额外的空间O(n)。 可以在不占用空间或没有空间的情况下完成吗?

2 个答案:

答案 0 :(得分:2)

我建议采用以下方法,当然必须对其进行测试,但我认为它应该有效。

如果您执行二叉树的按顺序遍历,您将按左右顺序找到节点。现在,我们可以检查节点是否是叶子,如果它是叶子,我们必须做两件事:

1. link the previous leaf to current leaf
2. update the current leaf as the previous

void inOrderTraversal(Node root, Node previous){
   if(root!=null){
      inOrderTraversal(root.left, previous);
      if(root.left==null && root.right==null){
         if(previous!=null)
            previous.right=root;
         previous=root;
      }
      inOrderTraversal(root.right, previous);
   }
}

通过这种方式,您可以获得更好的空间复杂度:O(1)。

答案 1 :(得分:1)

在你的算法中,不要将叶子存储在队列中,只需将前一个叶子的右指针指向当前叶子即可。

lastLeaf->right = currLeaf;
lastLeaf = currLeaf;
相关问题