剑指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

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值