【剑指offer】4.重建二叉树

题目

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。


分析

思路:
先来分析一下前序遍历和中序遍历得到的结果,

前序遍历第一位是根节点;
中序遍历中,根节点左边的是根节点的左子树,右边是根节点的右子树。

例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}。

首先,根节点 是{ 1 };
左子树是:前序{ 2,4,7 } ,中序{ 4,7,2 };
右子树是:前序{ 3,5,6,8 } ,中序{ 5,3,8,6 };

这时,如果我们把左子树和右子树分别作为新的二叉树,则可以求出其根节点,左子树和右子树。

利用上述递归方式就可以实现重建二叉树。

github链接如下:JZ04-重建二叉树


C++代码

#include <iostream>
using namespace std;
#include <vector> 

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) {
			int size = pre.size();
			int *Pre,*Vin;
			Pre = new int[size];
			Vin = new int[size]; 
			for(int i = 0 ; i < size ; i++){
				Pre[i] = pre[i];
				Vin[i] = vin[i];
			}
			TreeNode* root = this->Build(Pre,Vin,size);
			return root;
	    }
	    
	    TreeNode* Build(int* Pre,int* Vin,int size){
	    	if(!Pre || !Vin || size < 0){
				return NULL;
			}
	    	int root_index = 0;
	    	for(root_index = 0 ; root_index < size ; root_index++){
				if(Pre[0] == Vin[root_index]){
					break;
				}
			}
			
			if(root_index == size){
				return NULL;
			}
			
			TreeNode* root;
			root = new TreeNode(Pre[0]);
			if(root_index > 0){
				root->left = this->Build(Pre+1,Vin,root_index);
			}
			if(size - root_index - 1> 0){
				root->right = this->Build(Pre+root_index+1,Vin+root_index+1,size-root_index-1);
			}
			return root;
		}
	    
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

daipuweiai

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值