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 a binary tree node. 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()==0) 14 return NULL; 15 stack<TreeNode*>s; 16 TreeNode*root,*t; 17 int flag=0,i=0,j=0; 18 root=new TreeNode(preorder[0]); 19 t=root; 20 s.push(root); 21 i++; 22 while(i<preorder.size()) 23 { 24 if(!s.empty()&&s.top()->val==inorder[j]) 25 { 26 t=s.top(); 27 s.pop(); 28 flag=1; 29 j++; 30 } 31 else 32 { 33 if(flag==0) 34 { 35 t->left=new TreeNode(preorder[i]); 36 t=t->left; 37 s.push(t); 38 i++; 39 } 40 else 41 { 42 flag=0; 43 t->right=new TreeNode(preorder[i]); 44 t=t->right; 45 s.push(t); 46 i++; 47 } 48 } 49 } 50 return root; 51 } 52 };
方法二:递归