剑指offer 重建二叉树

  • 题目描述

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

  • 题目解析

看到题目想到的是递归求解。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    struct TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> in) {
		int size1 = pre.size();
		int size2 = in.size();
		if (size1 != size2 || size1 == 0 || size2 == 0)
			return NULL;

		TreeNode* ret = buildTree(pre, in);
		return ret;
	}

	struct TreeNode* buildTree(vector<int> pre, vector<int> in){
		int size = in.size();

		TreeNode* ret = new TreeNode(pre[0]);

		int lsize = 0, rsize = 0;
		vector<int> nextLPre, nextLIn;
		vector<int> nextRPre, nextRIn;
		bool flag = false;
		for (int i = 0; i < size; ++i){
			if (in[i] == pre[0]){
				flag = true;
			}
			else if(flag==false){
				lsize++;
				nextLPre.push_back(pre[i + 1]);
				nextLIn.push_back(in[i]);
			}
			else{
				nextRPre.push_back(pre[i]);
				nextRIn.push_back(in[i]);
			}
		}
		rsize = size - lsize - 1;
		if (lsize != 0)
			ret->left = buildTree(nextLPre, nextLIn);
		if (rsize != 0)
			ret->right = buildTree(nextRPre, nextRIn);
		return ret;
	}
};
弹钢琴的猫 /
Published under (CC) BY-NC-SA in categories 算法  tagged with 剑指offer  Tree