劍指Offer4.重建二叉樹
1.題目
輸入某二叉樹的前序周遊和中序周遊的結果,請重建出該二叉樹。假設輸入的前序周遊和中序周遊的結果中都不含重複的數字。例如輸入前序周遊序列{1,2,4,7,3,5,6,8}和中序周遊序列{4,7,2,1,5,3,8,6},則重建二叉樹并傳回。
2.基礎知識
- 前序周遊:先通路根結點,再通路左子結點,最後通路右子結點。
- 中序周遊:先通路左子結點,再通路根結點,最後通路右子結點。
- 後序周遊:先通路左子結點,再通路右子結點,最後通路根結點。
3.思路
中心還是使用遞歸思想,前序周遊序列中,第一個數字總是樹的根結點的值。在中序周遊序列中,根結點的值在序列的中間,左子樹的結點的值位于根結點的值的左邊,而右子樹的結點的值位于根結點的值的右邊。
4.代碼
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
if(pre.size() == 0){
return NULL;
}
vector<int> left_pre, right_pre, left_vin, right_vin;
TreeNode* head = new TreeNode(pre[0]);
int root = 0;
for(int i = 0; i < pre.size(); i++){
if(vin[i] == pre[0]){
root = i;
break;
}
}
for(int i = 0; i < root; i++){
left_vin.push_back(vin[i]);
left_pre.push_back(pre[i+1]);
}
for(int i = root+1; i < pre.size(); i++){
right_vin.push_back(vin[i]);
right_pre.push_back(pre[i]);
}
head->left = reConstructBinaryTree(left_pre,left_vin);
head->right = reConstructBinaryTree(right_pre,right_vin);
return head;
}
};
# -*- 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):
if len(pre) == 0:
return None
elif len(pre) == 1:
return TreeNode(pre[0])
else:
a = TreeNode(pre[0])
b = tin.index(pre[0])
a.left = self.reConstructBinaryTree(pre[1:b+1], tin[:b])
a.right = self.reConstructBinaryTree(pre[b+1:], tin[b+1:])
return a