标签:
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
1 class Solution { 2 public: 3 TreeNode* createTree(vector<int>& inorder,int instart,int inend,vector<int> &postorder,int poststart,int postend) 4 { 5 if(instart>inend) return NULL; 6 7 int root=postorder[postend]; 8 9 int index; 10 11 for(int i=instart;i<=inend;i++) 12 { 13 if(inorder[i]==root) 14 { 15 index=i; 16 break; 17 } 18 } 19 20 int len=index-instart; 21 TreeNode *left=createTree(inorder,instart,index-1,postorder,poststart,poststart+len-1); 22 TreeNode *right=createTree(inorder,index+1,inend,postorder,poststart+len,postend-1); 23 24 TreeNode *node=new TreeNode(root); 25 node->left=left; 26 node->right=right; 27 28 return node; 29 } 30 TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { 31 32 if(inorder.size()==0) return NULL; 33 34 TreeNode *head=createTree(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1); 35 return head; 36 } 37 };
【leetcode】Construct Binary Tree from Inorder and Postorder Traversal
标签:
原文地址:http://www.cnblogs.com/jawiezhu/p/4521058.html