/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> postorderTraversal(TreeNode *root) { vector<int> path; vector<TreeNode*> stack; if (root != NULL) { stack.push_back(root); } TreeNode* last = NULL; while(!stack.empty()) { TreeNode* cur = stack.back(); if (cur->left == NULL && cur->right == NULL) { path.push_back(cur->val); stack.pop_back(); last = cur; continue; } if (last != NULL && (cur->left == last || cur->right == last)) { path.push_back(cur->val); stack.pop_back(); last = cur; continue; } while (cur != NULL) { if (cur->right != NULL) stack.push_back(cur->right); if (cur->left != NULL) stack.push_back(cur->left); cur = cur->left; } } return path; } };
Note: Recursive solution is trivial, could you do it iteratively? 那就写个非递归的呗!通用算法见 LeetCode Binary Tree Inorder Traversal
第二轮:
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 2 / 3
return [3,2,1]
.
Note: Recursive solution is trivial, could you do it iteratively?
还是用老方法:
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 Frame { 11 public: 12 TreeNode* node; 13 int stage; 14 Frame(TreeNode* n = NULL, int s = -1) : node(n), stage(s) {} 15 }; 16 17 class Solution { 18 public: 19 vector<int> postorderTraversal(TreeNode *root) { 20 vector<int> res; 21 22 stack<Frame> stk; 23 stk.push(Frame(root, -1)); 24 25 while (!stk.empty()) { 26 Frame& cf = stk.top(); 27 28 if (cf.node == NULL) { 29 stk.pop(); 30 continue; 31 } 32 33 cf.stage++; 34 TreeNode* node = cf.node; 35 36 switch(cf.stage) { 37 case 0: stk.push(Frame(node->left)); break; 38 case 1: stk.push(Frame(node->right)); break; 39 case 2: 40 res.push_back(node->val); 41 stk.pop(); 42 } 43 } 44 return res; 45 } 46 };