题目:
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了不少时间)
时间: 2024-10-10 02:35:01