From bfc401f2a54b823ef4f94cc3051dcc54af481f0c Mon Sep 17 00:00:00 2001 From: Azureki Date: Wed, 22 Aug 2018 16:47:45 +0800 Subject: [PATCH] Construct Binary Tree from Preorder and Postorder Traversal --- lc889.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 lc889.py diff --git a/lc889.py b/lc889.py new file mode 100644 index 0000000..c73b2fd --- /dev/null +++ b/lc889.py @@ -0,0 +1,34 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def constructFromPrePost(self, pre, post): + """ + :type pre: List[int] + :type post: List[int] + :rtype: TreeNode + """ + + if not pre: + return None + root=TreeNode(pre[0]) + + if len(pre)>1: + i=post.index(pre[1]) + root.left=self.constructFromPrePost(pre[1:(i+2)],post[:(i+1)]) + root.right=self.constructFromPrePost(pre[(i+2):],post[(i+1):-1]) + + return root + + + + +s=Solution() +pre = [1,2,4,5,3,6,7] +post = [4,5,2,6,7,3,1] + +print(s.constructFromPrePost(pre,post)) \ No newline at end of file