【问题标题】:How to construct a Binary Tree from Inorder and Postorder Traversal iteratively?如何迭代地从中序和后序遍历构造二叉树?
【发布时间】:2021-09-11 04:39:42
【问题描述】:

从 Inorder 和 Postorder Traversal 迭代构造二叉树。

我已经看到了如何使用递归来做到这一点,但我正在寻找一个迭代构造二叉树的答案。

我为中序和前序编写了一个算法,但我想知道如何为中序和后序修改它?

注意:它是伪代码,“=”表示“==”

节点:

e: TElement
right: PNode (pointer to a Node)
left: PNode (pointer to a Node)

二叉树:

root: PNode

子算法树(前序,中序)

pre: preorder: Int[], inorder: Int[]

preOrderIndex<- 0;
inOrderIndex<-0;

Stack(s) 
root <- createNode(preorder[0])
push(s, root)

preOrderIndex<-preOrderIndex +1

While !empty(s)
    element(s, top) //which is the same as top = peak(s)
    
    if [top].e = inorder[inOrderIndex] 
        delete(s, top) //delete the element from the stack
        inOrderIndex<-inOrderIndex +1
    
        if inOrderIndex = length(inorder) 
            
            return root
        End if
        
        element(s, elem) 
        
        if !empty(s) and [elem].e = inorder[inOrderIndex]
            continue
        End if
        
       
        nod <- createNode(preorder[preOrderIndex])
        [top].right<-nod
        preOrderIndex<-preOrderIndex +1
        push(s,nod)
    Else
        nod <- createNode(preorder[preOrderIndex])
        [top].left<-nod
        preOrderIndex<-preOrderIndex +1
        push(s,nod)
    End if
End while

return root

结束子算法

编辑:我找到了答案

【问题讨论】:

  • “编辑:我找到了答案”——它是什么?如果您添加self answer,那么您可以将您的知识贡献给社区,以便将来与您有相同问题的其他人受益。谢谢。

标签: algorithm recursion tree iteration binary-tree


【解决方案1】:

当您有一个给定前序和中序遍历的有效解决方案时,您可以使用以下观察将其转换为给定后序和中序遍历的解决方案:

  • 中序遍历的逆序等于镜像树的中序遍历(左右交换)

  • 后序遍历的逆序等于镜像树的前序遍历

因此,对您的工作算法进行以下更改:

  • 在变量名中出现的任何地方都将 pre 重命名为 post
  • length(inorder)-1 初始化postOrderIndexinOrderIndex
  • 将它们的递增语句替换为递减语句
  • 将退出条件替换为if inOrderIndex &lt; 0
  • left 替换为right,反之亦然

【讨论】:

    猜你喜欢
    • 2014-12-30
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    相关资源
    最近更新 更多