題目
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。
例如,給出
前序遍歷 preorder = [3,9,20,15,7]
中序遍歷 inorder = [9,3,15,20,7]
返回如下的二叉樹:
3
/
9 20
/
15 7
限制:
0 <= 節點個數 <= 5000
代碼
Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# 思想:
# 1.得到前序根結點
# 2.搜索根節點在中序索引,劃分左右子樹
# 3.分別遞歸遍歷左右子樹
# 複雜度:O(N),N是節點數量,前提是建立哈希表再搜索根節點在中序索引會是O(1),以空間換時間
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
self.hashmap,self.po={},preorder
# 建立中序遍歷哈希表
for i in range(len(inorder)):
self.hashmap[inorder[i]]=i
return self.recur(0,0,len(inorder)-1) # 開啓遞歸,返回各子樹根節點
def recur(self, pre_root, in_left, in_right)->TreeNode:
# 子樹遞歸函數
# 輸入:前序根節點索引,中序子樹左邊界,中序子樹右邊界
# 輸出:子樹根節點
if in_left>in_right: return # 遞歸終止條件:左邊界>右邊界
root=TreeNode(self.po[pre_root]) # 建立根節點
i=self.hashmap[root.val] # 返回根節點在中序遍歷的索引
root.left=self.recur(pre_root+1,in_left,i-1) # 這裏的三個索引一定要理清
root.right=self.recur(pre_root+i-in_left+1,i+1,in_right)
return root
C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
unordered_map<int,int> hashmap;
vector<int> po;
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
po=preorder;
for (int i=0;i<inorder.size();i++) {
hashmap[inorder[i]]=i;
}
TreeNode* root=recur(0,0,inorder.size()-1);
return root;
}
TreeNode* recur(int pre_root,int in_left,int in_right) {
if (in_left>in_right) return NULL;
TreeNode* root=new TreeNode(po[pre_root]);
int i=hashmap[root->val];
root->left=recur(pre_root+1,in_left,i-1);
root->right=recur(pre_root+i-in_left+1,i+1,in_right);
return root;
}
};