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 binary tree * 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) { TreeNode* root = NULL; constructTree(preorder, inorder, 0, 0, preorder.size(), root); return root; } void constructTree(vector<int>& preorder, vector<int>& inorder, int s1, int s2, int len, TreeNode*& root) { if( len < 1 ) return ; root = new TreeNode( preorder[s1] ); //建立根节点 vector<int>::iterator iter = find( inorder.begin()+s2, inorder.begin()+s2+len, root->val ); //在中序序列中找到根节点位置 int leftnum = iter - ( inorder.begin() + s2 ); //左子树节点个数 int rightnum = len - leftnum - 1; //右子树节点个数 constructTree( preorder, inorder, s1+1, s2, leftnum, root->left ); //构建左子树 constructTree( preorder, inorder, s1+leftnum+1, s2+leftnum+1, rightnum, root->right); //构建右子树 } };
Given inorder and postorder traversal of a tree, construct the binary tree.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { TreeNode* root = NULL; constructTree(inorder, postorder, 0, 0, inorder.size(), root); return root; } void constructTree(vector<int>& inorder, vector<int>& postorder, int s1, int s2, int len, TreeNode*& root) { if( len < 1 ) return ; int rootIndex = s2 + len - 1; //后序序列中,最后一个元素是根元素 root = new TreeNode( postorder[rootIndex] ); //在中序序列中找到根元素的位置 vector<int>::iterator iter = find( inorder.begin() + s1, inorder.begin() + s1 + len, postorder[rootIndex] ); int leftNum = iter - (inorder.begin() + s1); //计算左子树节点的数目 int rightNum = len - leftNum - 1; //计算右子树节点的数目 constructTree( inorder, postorder, s1, s2, leftNum, root->left); //构建左子树 constructTree( inorder, postorder, s1+leftNum+1, s2+leftNum, rightNum, root->right); //构建右子树 } };
posted on 2014-08-12 23:38 bug睡的略爽 阅读(209) 评论(0) 编辑 收藏 举报