题目:
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()==0 || inorder.size()==0 ) return NULL; return Solution::buildTreePI(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1); } 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(-1); 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+1, beginP+leftSize, inorder, beginI, rootPosInorder-1); root->right = Solution::buildTreePI(preorder, endP-rightSize+1, endP, inorder, rootPosInorder+1, 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, 0, preorder.size()-1, inorder, 0, inorder.size()-1); } 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+1, bp+left_range, inorder, bi, bi+left_range-1); root->right = Solution::build(preorder, bp+left_range+1, ep, inorder, bi+left_range+1, 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; } };