劍指offer 第4題 重建二叉樹
阿新 • • 發佈:2019-01-11
描述:
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
思路:
遞迴,basecase為如果pre元素個數為0時,返回None,如果pre元素個數為1時返回葉子節點
程式碼:
class Solution: # 返回構造的TreeNode根節點 def reConstructBinaryTree(self, pre, tin): # write code here if len(pre) == 0: return None elif len(pre) == 1: return TreeNode(pre[0]) root = TreeNode(pre[0]) index = tin.index(pre[0]) root.left = self.reConstructBinaryTree(pre[1:index + 1], tin[:index]) root.right = self.reConstructBinaryTree(pre[index + 1:], tin[index + 1:]) return root
結果:
執行時間:54ms
佔用記憶體:5724k