1. 程式人生 > >二叉樹前序、中序遍歷得到後序遍歷

二叉樹前序、中序遍歷得到後序遍歷

() level struct OS spa str sel src []

二叉樹的前序遍歷為:{1,2,4,7,3,5,6,8},中序遍歷為:{4,7,2,1,5,3,8,6},求後序遍歷

 技術分享圖片

# -*- coding:utf-8 -*-
class Node:
    def __init__(self, x):
        self.data = x
        self.lchild = None
        self.rchild = None
class Solution:

    def __init__(self):
        self.list=[]

    def reConstructBinaryTree(self, pre, tin):
        
if len(tin)==0 or len(pre)==0: self.list.append(Node(-1)) return Node(-1) data = pre.pop(0) root=Node(data) index=tin.index(data) #遞歸得到後序遍歷 root.lchild=self.reConstructBinaryTree(pre,tin[0:index]) root.rchild=self.reConstructBinaryTree(pre,tin[index+1:]) self.list.append(root)
return root #層次遍歷 def level_queueAndStack(self,root): if root==None: return stack_1=[] stack_2=[] stack_1.append(root) stack_2.append(root) while stack_1: node=stack_1.pop(0) if node.lchild: stack_1.append(node.lchild) stack_2.append(node.lchild)
if node.rchild: stack_1.append(node.rchild) stack_2.append(node.rchild) while stack_2: print stack_2.pop(0).data, s=Solution() s.reConstructBinaryTree([1,2,4,7,3,5,6,8],[4,7,2,1,5,3,8,6]) #輸出樹的後序遍歷 l=[i.data for i in s.list if i.data!=-1] print l s.level_queueAndStack(s.list.pop())

輸出結果:

[7, 4, 2, 5, 8, 6, 3, 1]
1 2 3 4 -1 5 6 -1 7 -1 -1 8 -1 -1 -1 -1 -1

二叉樹前序、中序遍歷得到後序遍歷