题目:
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
思路:
与 http://blog.youkuaiyun.com/lanxu_yy/article/details/17383007类似,但是过程相反。代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorder;
vector<int> inorder;
int cur;
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
if(preorder.size() == 0)
return NULL;
else
{
cur = 0;
this->preorder = preorder;
this->inorder = inorder;
return buildSubTree(0, inorder.size()-1);
}
}
TreeNode* buildSubTree(int from, int to)
{
TreeNode * root = new TreeNode(preorder[cur]);
int index = findValInInOrder(preorder[cur]);
cur++;
if(index <= from)
{
root->left = NULL;
}
else
{
root->left = buildSubTree(from, index-1);
}
if(index >= to)
{
root->right = NULL;
}
else
{
root->right = buildSubTree(index+1,to);
}
return root;
}
int findValInInOrder(int val)
{
for(int i=0;i<inorder.size();i++)
{
if(val == inorder[i])
{
return i;
}
}
return -1;
}
};

本文介绍了一种通过前序遍历和中序遍历构建二叉树的方法。利用递归方式,找到根节点,并划分左右子树,最终完成整棵树的构建。
3491

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



