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?
/** * 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>result; TreeNode*node=root; stack<TreeNode*>st; stack<bool>st_flag; while(node){ st.push(node); st_flag.push(false); node=node->left; } while(!st.empty()){ bool status = st_flag.top(); if(!status){ //访问右子树 st_flag.pop(); st_flag.push(true); node = st.top(); node=node->right; while(node){ st.push(node); st_flag.push(false); node=node->left; } } else{ //访问当前结点 st_flag.pop(); node = st.top(); st.pop(); result.push_back(node->val); } } return result; } };
LeetCode: Binary Tree Postorder Traversal [145],布布扣,bubuko.com
LeetCode: Binary Tree Postorder Traversal [145]
原文:http://blog.csdn.net/harryhuang1990/article/details/35780409