Binary Tree Postorder Traversal
Binary Tree Postorder Traversal
Total Accepted: 82814 Total Submissions: 244246 Difficulty: Hard
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 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> res; stack<pair<TreeNode*,bool>> paths; TreeNode* p = root; while(p || !paths.empty()){ while(p){ paths.push(make_pair(p,false)); p = p->left; } while(!paths.empty()){ pair<TreeNode*,bool>& node = paths.top(); if(node.second){ res.push_back(node.first->val); paths.pop(); }else{ p = node.first->right; node.second = true; break; } } } return res; } };
写者:zengzy
出处: http://www.cnblogs.com/zengzy
标题有【转】字样的文章从别的地方转过来的,否则为个人学习笔记