重建二叉樹—遞迴
阿新 • • 發佈:2020-07-23
二叉樹重建
-
問題:輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重 復的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
-
解決:
#遞迴一 # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def reConstructBinaryTreeCore(self,pre,pre_start,pre_end,tin,tin_start,tin_end): if pre_start > pre_end or tin_start > tin_end: return None root = TreeNode(pre[pre_start]) for i in range(tin_start,tin_end+1): if pre[pre_start] == tin[i]: root.left = self.reConstructBinaryTreeCore(pre,pre_start+1,i-tin_start+pre_start,tin,tin_start,i-1) root.right = self.reConstructBinaryTreeCore(pre,i-tin_start+pre_start+1,pre_end,tin,i+1,tin_end) break return root # 返回構造的TreeNode根節點 def reConstructBinaryTree(self, pre, tin): # write code here if len(pre)==0 or len(tin)==0: return None return self.reConstructBinaryTreeCore(pre,0,len(pre)-1,tin,0,len(tin)-1) #遞迴二 class Solution: # 返回構造的TreeNode根節點 def reConstructBinaryTree(self, pre, tin): # write code here if not pre or not tin: return root = TreeNode(pre[0]) i = tin.index(pre[0]) root.left = self.reConstructBinaryTree(pre[1:i+1], tin[:i]) root.right = self.reConstructBinaryTree(pre[i+1:], tin[i+1:]) return root