劍指offer編程題--重建二叉樹

題目描述:

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

 

方案:在二叉樹的前序遍歷序列中,第一個數字總是樹的根節點的值;

  在二叉樹的中序遍歷序列中,根節點的值在序列的中間,根節點左側的值爲左子樹的節點值,根節點右側的值爲右子樹的節點值。

 

Eg:前序遍歷序列:{1,2,4,3,5,6},中序遍歷序列{4,2,1,5,3,6}

方案1與方案2只是遞歸結束條件不同;如下表格表示的是左子樹的遞歸結束步驟。

 

方案1:

i

start_pre

end_pre

start_vin

end_vin

 

0

5

0

5

2

1

2

0

1

1

2

2

0

0

0

3

2

0

-1

 

方案2:

start_pre

end_pre

start_vin

end_vin

left_tmp

left_length

0

5

0

5

2

2

1

2

0

1

1

1

2

2

0

0

0

0

 

 

/**

 * Definition for binary tree

 * struct TreeNode {

 *     int val;

 *     TreeNode *left;

 *     TreeNode *right;

 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}

 * };

 */

 

方案1:

class Solution {

public:

TreeNode* constructCore(vector<int> pre, vector<int> vin, int start_pre, int end_pre, int start_vin, int end_vin){

TreeNode* root = new TreeNode(pre[start_pre]);

       //遞歸結束的條件

if (start_pre > end_pre || start_vin > end_vin){

return NULL;

}

for (int i = start_vin; i<=end_vin; i++){

if (vin[i] == pre[start_pre]){

root->left = constructCore(pre, vin, start_pre + 1, start_pre + i - start_vin, start_vin, i - 1);

root->right = constructCore(pre, vin, start_pre + i - start_vin + 1, end_pre, i + 1, end_vin);

break;

}

}

return root;

}

 

 

方案2:

class Solution {

public:

TreeNode* constructCore(vector<int> pre, vector<int> vin, int start_pre, int end_pre, int start_vin, int end_vin){

TreeNode* root = new TreeNode(pre[start_pre]);

        //遞歸結束條件

if (start_pre == end_pre && start_vin == end_vin && pre[start_pre] == vin[start_pre]){

return root;

}

int left_tmp = 0;

for (int i = start_vin; i <= end_vin; i++){

if (vin[i] == pre[start_pre]){

    left_tmp = i;

break;

}

}

    int left_length = left_tmp - start_vin;

if(left_length >0){

root->left=constructCore(pre,vin,start_pre+1,start_pre+left_length,start_vin,left_tmp-1);

}

if(left_length < end_pre - start_pre){

root->right=constructCore(pre,vin,start_pre+left_length+1,end_pre,left_tmp+1,end_vin)

}

return root;

}

 

 

TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> vin) {

if (pre.size() <= 0 || vin.size() <= 0){

return NULL;

}

return constructCore(pre, vin, 0, pre.size() - 1, 0, vin.size() - 1);

}

};

參考鏈接:

https://blog.csdn.net/qianhangkang/article/details/79527572

https://github.com/zhedahht/CodingInterviewChinese2/blob/master/07_ConstructBinaryTree/ConstructBinaryTree.cpp

《劍指offer》P62

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章