题目
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
思路
主要是根据前序遍历和中序遍历的特点解决这个题目。
1、确定树的根节点。树根是当前树中所有元素在前序遍历中最先出现的元素。
2、求解树的子树。找出根节点在中序遍历中的位置,根左边的所有元素就是左子树,根右边的所有元素就是右子树。若根节点左边或右边为空,则该方向子树为空;若根节点边和右边都为空,则根节点已经为叶子节点。
3、递归求解树。将左子树和右子树分别看成一棵二叉树,重复1、2、3步,直到所有的节点完成定位
代码
/*---------------------------------------
* 日期:2015-04-28
* 作者:SJF0115
* 题目: 105.Construct Binary Tree from Preorder and Inorder Traversal
* 网址:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
* 结果:AC
* 来源:LeetCode
* 博客:
-----------------------------------------*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x):val(x),left(nullptr),right(nullptr){}
};
class Solution {
public:
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
int size = preorder.size();
if(size <= 0){
return nullptr;
}//if
return PreInBuildTree(preorder,inorder,0,0,size);
}
private:
TreeNode* PreInBuildTree(vector<int> &preorder,vector<int> &inorder,int preIndex,int inIndex,int size){
if(size <= 0){
return nullptr;
}//if
// 根节点
TreeNode* root = new TreeNode(preorder[preIndex]);
// 寻找根节点在中序遍历数组的下标
int index = 0;
for(int i = 0;i < size;++i){
if(preorder[preIndex] == inorder[inIndex+i]){
index = inIndex+i;
break;
}//if
}//for
// 左子树个数
int leftSize = index - inIndex;
// 右子树个数
int rightSize = size - leftSize - 1;
// 左子树
root->left = PreInBuildTree(preorder,inorder,preIndex+1,inIndex,leftSize);
// 右子树
root->right = PreInBuildTree(preorder,inorder,preIndex+1+leftSize,index+1,rightSize);
return root;
}
};
void PostOrder(TreeNode* root){
if(root){
PostOrder(root->left);
PostOrder(root->right);
cout<<root->val<<endl;
}//if
}
int main(){
Solution solution;
vector<int> preorder = {1,2,4,8,5,3,6,7};
vector<int> inorder = {8,4,2,5,1,6,3,7};
TreeNode* root = solution.buildTree(preorder,inorder);
// 输出
PostOrder(root);
return 0;
}
运行时间
[LeetCode]*105.Construct Binary Tree from Preorder and Inorder Traversal
原文:http://blog.csdn.net/sunnyyoona/article/details/45343173