3.4 重建二叉树

重建二叉树

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
struct TreeNode {
     int val;
     TreeNode *left;
     TreeNode *right;
     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 };

 TreeNode* constructTree(vector<int> pre, int preStart, int preEnd, vector<int> in, int inStart, int inEnd) {
	 if (preStart > preEnd || inStart > inEnd) {
		 return NULL;
	 }

	 if (pre.size() <= preEnd || in.size() <= inEnd) {
		 return NULL;
	 }

	 // 先序遍历的第一个为根节点
	 int value = pre[preStart];				

	 // 找出先序遍历的值 在中序遍历的位置
	 int valIndex = inStart;		
	 while (valIndex <= inEnd && in[valIndex] != value) {
		 valIndex++;
	 }
	 
	 // 再中序遍历中没有找到
	 if (valIndex > inEnd) {
		 return NULL;
	 }

	 TreeNode* node = new TreeNode(value);
	 node->left = constructTree(pre, preStart + 1, preStart + valIndex - inStart, in, inStart, valIndex - 1);
	 node->right = constructTree(pre, preStart + valIndex - inStart + 1, preEnd, in, valIndex + 1, inEnd);
	 return node;
}


 TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> vin) {
	 if (pre.size() > 0 && vin.size() > 0 && pre.size() == vin.size()) {
		 return constructTree(pre, 0, pre.size() - 1, vin, 0, vin.size() - 1);
	 }
	 return NULL;
 }
 

测试

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_37518595/article/details/84662364