145. Binary Tree Postorder Traversal (Stack, Tree)
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?
class Solution { public: vector<int> postorderTraversal(TreeNode *root) { vector<int> result; if(!root) return result; stack<MyNode*> treeStack; MyNode* myRoot = new MyNode(root); MyNode* current, *newNode; treeStack.push(myRoot); while(!treeStack.empty()) { current = treeStack.top(); treeStack.pop(); if(!current->flag) { current->flag = true; treeStack.push(current); if(current->node->right) { newNode = new MyNode(current->node->right); treeStack.push(newNode); } if(current->node->left) { newNode = new MyNode(current->node->left); treeStack.push(newNode); } } else { result.push_back(current->node->val); } } return result; } struct MyNode { TreeNode* node; bool flag; //indicate if the node has been visited MyNode(TreeNode* x) : node(x),flag(false) {} }; };
法II: 不重新定义结构,以root->right->left的顺序访问节点,最后逆序。
/** * Definition for a binary tree node. * 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> result; if(!root) return result; stack<TreeNode*> treeStack; TreeNode* current; treeStack.push(root); //visit in order root->right->left while(!treeStack.empty()) { current = treeStack.top(); treeStack.pop(); result.push_back(current->val); if(current->left) treeStack.push(current->left); if(current->right) treeStack.push(current->right); } //reverse result int size = result.size(); int hsize = size>>1; int tmp; for(int i = 0; i < hsize; i++){ tmp = result[i]; result[i]=result[size-1-i]; result[size-1-i]=tmp; } return result; } };