construct-binary-tree-from-preorder-and-inorder
2017-05-24 22:05
417 查看
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the 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) { if(preorder.size()==0||preorder.size()!=inorder.size()) return NULL; return recurbuild(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1); } TreeNode *recurbuild(vector<int> &preorder,vector<int> &inorder,int prebegin, int preend,int inbegin,int inend){ if(prebegin>preend) return NULL; TreeNode* root=new TreeNode(preorder[prebegin]); auto pos=find(inorder.begin(),inorder.end(),preorder[prebegin]); int len=pos-inorder.begin(); root->left=recurbuild(preorder,inorder,prebegin+1,prebegin+len-inbegin,inbegin,len-1); root->right=recurbuild(preorder,inorder,prebegin+len-inbegin+1,preend,len+1,inend); return root; } };
相关文章推荐
- leetcode — construct-binary-tree-from-preorder-and-inorder-traversal
- construct-binary-tree-from-preorder-and-inorder-traversal
- construct-binary-tree-from-preorder-and-inorder-traversal
- leetcode — construct-binary-tree-from-preorder-and-inorder-traversal
- leetcode第44题(construct-binary-tree-from-preorder-and-inorder-……)
- construct-binary-tree-from-preorder-and-inorder-traversal
- *Leetcode_construct-binary-tree-from-preorder-and-inorder-traversal
- construct-binary-tree-from-preorder-and-inorder-traversal Java code
- 【construct-binary-tree-from-preorder-and-inorder-traversal】
- construct-binary-tree-from-preorder-and-inorder-traversal
- 【construct-binary-tree-from-preorder-and-inorder-traversal】
- leetcode--construct_binary_tree_from_preorder_and_inorder_traversal
- 【construct-binary-tree-from-preorder-and-inorder-traversal】
- construct-binary-tree-from-preorder-and-inorder-traversal——前序和中序求二叉树
- LeetCode--construct-binary-tree-from-preorder-and-inorder-traversal
- lintcode construct-binary-tree-from-inorder-and-postorder-traversal 中序遍历和后序遍历树构造二叉树
- construct-binary-tree-from-inorder-and-postorder-traversal Java code
- leetcode — construct-binary-tree-from-inorder-and-postorder-traversal
- construct-binary-tree-from-inorder-and-postorder-traversal
- leetcode--ConstructBinaryTreefromInorderandPostorderTraversal