[Leetcode] Construct binary tree from inorder and postorder travesal 利用中序和後續遍歷構造二叉樹
阿新 • • 發佈:2017-06-08
post right clas end opened tree 數組 isp solution
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,2,3,4,5,6,#}的後序遍歷為4->5->2->6->3->1;中序遍歷為:4->2->5->1->6->3。
故,遞歸的整體思路是,找到根節點,然後遍歷左右子樹。
方法一:遞歸
值得註意的是:遞歸過程中,起始點的選取。Grandyang對下標的選取有較為詳細的說明。
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 classSolution { 11 public: 12 TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) 13 { 14 int len=inorder.size(); 15 return build(inorder,0,len-1,postorder,0,len-1); 16 } 17 TreeNode *build(vector<int> &inorder,int inBeg,int inEnd,vector<int> &postorder,int postBeg,int postEnd) 18 { 19 if(inBeg>inEnd||postBeg>postEnd) return NULL; 20 TreeNode *root=new TreeNode(postorder[postEnd]); 21 22 for(int i=0;i<postorder.size();++i) 23 { 24 if(inorder[i]==postorder[postEnd]) 25 { 26 root->left=build(inorder,inBeg,i-1,postorder,postBeg,postBeg+i-1-inBeg); 27 root->right=build(inorder,i+1,inEnd,postorder,postBeg+i-inBeg,postEnd-1); 28 } 29 } 30 return root; 31 } 32 };
方法二:
利用棧。這個方法是以前看到出處也尷尬的忘了,分析過程等我再次看懂了再補上。這種方法改變了數組。
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> &inorder, vector<int> &postorder) 13 { 14 if(inorder.size()==0) return NULL; 15 TreeNode* p; 16 TreeNode* root; 17 stack<TreeNode*> stn; 18 19 root=new TreeNode(postorder.back()); 20 stn.push(root); 21 postorder.pop_back(); 22 23 while(true) 24 { 25 if(inorder.back()==stn.top()->val) 26 { 27 p=stn.top(); 28 stn.pop(); 29 inorder.pop_back(); 30 31 if(inorder.size()==0) break; 32 if(stn.size()&&inorder.back()==stn.top()->val) 33 continue; 34 35 p->left=new TreeNode(postorder.back()); 36 postorder.pop_back(); 37 stn.push(p->left); 38 } 39 else 40 { 41 p=new TreeNode(postorder.back()); 42 postorder.pop_back(); 43 stn.top()->right=p; 44 stn.push(p); 45 } 46 } 47 return root; 48 } 49 };View Code
[Leetcode] Construct binary tree from inorder and postorder travesal 利用中序和後續遍歷構造二叉樹