【Construct Binary Tree from Preorder and Inorder Traversal】cpp

题目:

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

代码:

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if ( preorder.size()== || inorder.size()== ) return NULL;
return Solution::buildTreePI(preorder, , preorder.size()-, inorder, , inorder.size()-);
}
static TreeNode* buildTreePI(
vector<int>& preorder,
int beginP, int endP,
vector<int>& inorder,
int beginI, int endI)
{
// terminal condition & corner case
if ( beginP>endP ) return NULL;
// resurisve process
TreeNode *root = new TreeNode(-);
root->val = preorder[beginP];
// find the root node in inorder traversal
int rootPosInorder = beginI;
for ( int i = beginI; i <= endI; ++i )
{
if ( inorder[i]==root->val ) { rootPosInorder=i; break;}
}
int leftSize = rootPosInorder - beginI;
int rightSize = endI - rootPosInorder;
root->left = Solution::buildTreePI(preorder, beginP+, beginP+leftSize, inorder, beginI, rootPosInorder-);
root->right = Solution::buildTreePI(preorder, endP-rightSize+, endP, inorder, rootPosInorder+, endI);
return root;
}
};

tips:

经典题目。直接学习高手代码

http://fisherlei.blogspot.sg/2013/01/leetcode-construct-binary-tree-from.html

http://bangbingsyb.blogspot.sg/2014/11/leetcode-construct-binary-tree-from.html

这里注意在递归传递vector元素下标的时候,一定是绝对下标(一开始疏忽写成了相对下标,debug了不少时间)

=========================================

第二次过这道题,大体思路还记得,顺着思路摸了下来,代码改了一次AC了。注意每次要找到的是preorder[bp]而不是preorder[0]。

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder)
{
return Solution::build(preorder, , preorder.size()-, inorder, , inorder.size()-);
}
TreeNode* build(
vector<int>& preorder, int bp, int ep,
vector<int>& inorder, int bi, int ei
)
{
if ( bp>ep || bi>ei ) return NULL;
TreeNode* root = new TreeNode(preorder[bp]);
int pos = Solution::findPos(inorder, bi, ei, preorder[bp]);
int left_range = pos - bi;
root->left = Solution::build(preorder, bp+, bp+left_range, inorder, bi, bi+left_range-);
root->right = Solution::build(preorder, bp+left_range+, ep, inorder, bi+left_range+, ei);
return root;
}
int findPos(vector<int>& order, int begin, int end, int val)
{
for ( int i=begin; i<=end; ++i ) if (order[i]==val) return i;
}
};
上一篇:py库: xlwt 、xlrd (写读EXCEL文件)


下一篇:Node.js:连接 MySQL