[剑指Offer]笔记4.重建二叉树 C++实现

Problem Description

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

Mentality

一看到二叉树,就会想到递归。本题给出前序序列和中序序列,前序序列是根、左、右,中序序列是左、根、右。
1.可以通过前序序列的第一个元素,把中序序列划分为左子树和右子树
2.同样可以通过中序序列中根元素的下标,将前序序列划分为左子树和右子树
3.再递归调用函数,根节点左分支由前序序列的左子树和中序序列的左子树递归获得,而右分支则由前序序列的右子树和中序序列的右子树递归获得。

Other Details

1.用vector记录前序序列的左右子树、中序序列的左右子树。
通过vector的push_back方法,在vector数组后面追加元素。
官方文档:

void push_back (const value_type& val);

Function:Add element at the end
Adds a new element at the end of the vector, after its current last element. The content of val is copied (or moved) to the new element.

This effectively increases the container size by one, which causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity.

2.可先判断传入的两个序列长度是否为0。
是则返回空,结束程序,否则执行之后的操作。

Code (C++)

/**
 * Definition for binary tree
 * 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) {
        if (pre.size() == 0 || vin.size() == 0)
			return NULL;
		int len = vin.size();
		TreeNode* p = (TreeNode*)malloc(sizeof(TreeNode));
		p->val = pre[0]; p->left = p->right = 0;

		int root(0);//记录根在中序列中的下标
		for (int i = 0; i < len; i++)
			if (vin[i] == pre[0]) {
				root = i;
				break;
			}

		vector<int> pre_left, pre_right, vin_left, vin_right;
		for (int i = 0; i < root; i++) {
			pre_left.push_back(pre[i + 1]);
			vin_left.push_back(vin[i]);
		}
		for (int i = root + 1; i < len; i++) {
			pre_right.push_back(pre[i]);
			vin_right.push_back(vin[i]);
		}
		p->left = reConstructBinaryTree(pre_left, vin_left);
		p->right = reConstructBinaryTree(pre_right, vin_right);
		return p;
    }
};

已通过所有的测试用例,欢迎指正批评(´▽`ʃ♡ƪ)

发布了19 篇原创文章 · 获赞 10 · 访问量 1201

猜你喜欢

转载自blog.csdn.net/qq_38655181/article/details/105228046