1. 程式人生 > >劍指offer(4):重建二叉樹

劍指offer(4):重建二叉樹

turn return null ptr 不存在 n) 地址 iterator eno

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重復的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。

思路:

1.前序遍歷的vector<int> pre中的第一個數為當前數的根節點, 在中序遍歷的結果vector<int> vin中找到該數的位置

2.則左邊的部分是左子樹的中序遍歷結果, 右邊的部分是右子樹中序遍歷的結果,

3.再對應到前序遍歷結果pre中, 前一部分是左子樹的前序遍歷結果, 後一部分是右子樹的前序遍歷結果。

4.四組vector再分成左右兩組, 遞歸返回當前節點地址。

5.如果輸入vector長度為0,則為空,不存在對應子樹,返回nullptr.

class Solution {
public:
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        if(pre.size() == 0 || vin.size() == 0) return nullptr;
        
        vector<int>::iterator it_pre = pre.begin();
        TreeNode* current_Root = new
TreeNode(pre[0]); vector<int>::iterator it_vin = find(vin.begin(), vin.end(),current_Root->val); auto num_left = distance(vin.begin(), it_vin); auto num_right = distance(it_vin, vin.end()) -1; vector<int> pre_left(it_pre + 1, it_pre + num_left + 1
); vector<int> pre_right(it_pre + num_left +1, pre.end()); vector<int> vin_left(vin.begin(), vin.begin() + num_left); vector<int> vin_right(it_vin +1, vin.end()); current_Root->left = reConstructBinaryTree(pre_left, vin_left); current_Root->right = reConstructBinaryTree(pre_right, vin_right); return current_Root; } };

劍指offer(4):重建二叉樹