标签:style blog io color ar os for sp div
给定中序遍历inorder和后序遍历postorder, 请构造出二叉树.
算法思路: 设后序遍历为po, 中序遍历为io.
代码:
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 if(inorder.size() == 0)return NULL; 14 TreeNode *p; 15 TreeNode *root; 16 stack<TreeNode *> stn; 17 18 root = new TreeNode(postorder.back()); 19 stn.push(root); 20 postorder.pop_back(); 21 22 while(true) 23 { 24 if(inorder.back() == stn.top()->val) 25 { 26 p = stn.top(); 27 stn.pop(); 28 inorder.pop_back(); 29 if(inorder.size() == 0) break; 30 if(stn.size() && inorder.back() == stn.top()->val) 31 continue; 32 p->left = new TreeNode(postorder.back()); 33 postorder.pop_back(); 34 stn.push(p->left); 35 } 36 else 37 { 38 p = new TreeNode(postorder.back()); 39 postorder.pop_back(); 40 stn.top()->right = p; 41 stn.push(p); 42 } 43 } 44 return root; 45 } 46 };
[LeetCode系列] 从中序遍历和后序遍历序列构造二叉树(迭代解法)
标签:style blog io color ar os for sp div
原文地址:http://www.cnblogs.com/lancelod/p/4073739.html