牛客網 劍指offer JZ4 重建二叉樹
阿新 • • 發佈:2021-07-16
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。
例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
對於pre ,每次pop的資料,就是最上方的root
對於tin,每次用pre.pop() 之後的數值為軸,分割前後樹
class Solution: # 返回構造的TreeNode根節點 def reConstructBinaryTree(self, pre, tin): if not pre or not tin:return None node = TreeNode(pre.pop(0)) mid = tin.index(node.val) node.left = self.reConstructBinaryTree(pre,tin[:mid]) node.right = self.reConstructBinaryTree(pre,tin[mid+1:]) return node
建立樹
class TreeNode: def __init__(self, x): self.val = x self.left= None self.right = None
pop() 函式用於移除列表中的一個元素(預設最後一個元素),並且返回該元素的值。
list.pop([index=-1])