遞歸最重要的兩部分:遞歸體和邊界條件
題目:輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
思路:前序遍歷的第一個元素一定是根節點,創建根節點
找到根節點在中序遍歷的位置,那麼這個節點左邊的節點全是它的左子樹。右邊的全是它的右子樹,能確定左右子樹的數量。
然後使用遞歸,構建它的左右子樹
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
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(root.val)
root.left = self.reConstructBinaryTree(pre[1:i+1],tin[:i])
root.right = self.reConstructBinaryTree(pre[i+1:],tin[i+1:])
return root