Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Subscribe to see which companies asked this question
思路分析:
题意:也就是根据树的前序中序遍历来重构二叉树。
There is an example.
_______7______ / \ __10__ ___2 / \ / 4 3 _8 \ / 1 11
The preorder and inorder traversals for the binary tree above is:
preorder = {7,10,4,3,1,2,8,11}
inorder = {4,10,3,1,7,11,8,2}
The first node in preorder alwasy the root of the tree. We can break the tree like:
1st round:
preorder: {7}, {10,4,3,1}, {2,8,11}
inorder: {4,10,3,1}, {7}, {11, 8,2}
_______7______
/ \
{4,10,3,1} {11,8,2}
Since we alreay find that {7} will be the root, and in "inorder" sert, all the data in the left of {7} will construct the left sub-tree. And the right part will construct a right sub-tree. We can the left and right part agin based on the preorder.
2nd round
left part right part
preorder: {10}, {4}, {3,1} {2}, {8,11}
inorder: {4}, {10}, {3,1} {11,8}, {2}
_______7______ / \ __10__ ___2 / \ / 4 {3,1} {11,8}
see that, {10} will be the root of left-sub-tree and {2} will be the root of right-sub-tree.
Same way to split {3,1} and {11,8}, yo will get the complete tree now.
_______7______ / \ __10__ ___2 / \ / 4 3 _8 \ / 1 11
So, simulate this process from bottom to top with recursion as following code.
代码如下:
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution_105_ConstructBinaryTreefromPreorderandInorderTraversal
{
public:
TreeNode *BuildTreePI(vector<int> &preorder, vector<int> &inorder, int p_s, int p_e, int i_s, int i_e)
{
int pivot = preorder[p_s];
int i = i_s;
for (; i < i_e; i++)
{
if (inorder[i] == pivot)
{
break;
}
}
int length1 = i - i_s - 1; //中序遍历中的root在向量中的下标
int length2 = i_e - i - 1; //中序遍历中从后向前的元素个数
TreeNode *node = new TreeNode(pivot);
node->left = BuildTreePI(preorder, inorder, p_s + 1, length1 + p_s + 1, i_s, i - 1);
node->right = BuildTreePI(preorder, inorder, p_e - length2, p_e, i + 1, i_e);
}
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder)
{
return BuildTreePI(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1);
}
};
本文介绍了一种根据二叉树的前序和中序遍历序列重建该二叉树的方法。通过递归方式划分左子树和右子树,并给出具体的实现代码。
3497

被折叠的 条评论
为什么被折叠?



