construct-binary-tree-from-preorder-and-inorder-traversal——前序和中序求二叉树
Posted 鸭子船长
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了construct-binary-tree-from-preorder-and-inorder-traversal——前序和中序求二叉树相关的知识,希望对你有一定的参考价值。
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { 13 if(preorder.size()!=inorder.size()) return NULL; 14 return build(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1); 15 } 16 17 TreeNode *build(vector<int> &preorder, vector<int> &inorder,int s1,int e1,int s2,int e2){ 18 if(s1>e1||s2>e2) return NULL; 19 if(s1==e1) return new TreeNode(preorder[s1]); 20 TreeNode *res=new TreeNode(preorder[s1]); 21 int tmp=preorder[s1]; 22 int index=0; 23 while((s2+index)<=e2){ 24 if(inorder[s2+index]==tmp) 25 break; 26 index++; 27 } 28 res->left=build(preorder,inorder,s1+1,s1+index,s2,s2+index-1); 29 res->right=build(preorder,inorder,s1+index+1,e1,s2+index+1,e2); 30 return res; 31 } 32 };
以上是关于construct-binary-tree-from-preorder-and-inorder-traversal——前序和中序求二叉树的主要内容,如果未能解决你的问题,请参考以下文章