leetcode || 145、Binary Tree Postorder Traversal
2015-05-05 10:34
369 查看
problem:
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree
return
Note: Recursive solution is trivial, could you do it iteratively?
Hide Tags
Tree Stack
题意:非递归后续遍历二叉树
thinking:
(1)非递归后续遍历二叉树的方法比较抽象,要借助两个stack
(2)采用双stack倒换,第一个stack出一次栈,将两个孩子(先左后右)入栈,出栈的节点保存到第二个stack。对第二个stack依次出栈即得到后续遍历的结果。
code:
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?
Hide Tags
Tree Stack
题意:非递归后续遍历二叉树
thinking:
(1)非递归后续遍历二叉树的方法比较抽象,要借助两个stack
(2)采用双stack倒换,第一个stack出一次栈,将两个孩子(先左后右)入栈,出栈的节点保存到第二个stack。对第二个stack依次出栈即得到后续遍历的结果。
code:
class Solution { public: vector<int> postorderTraversal(TreeNode* root) { stack<TreeNode *> input; stack<TreeNode *> output; vector<int> ret; if(root==NULL) return ret; TreeNode *node = root; input.push(node); while(!input.empty()) { node=input.top(); input.pop(); output.push(node); if(node->left!=NULL) input.push(node->left); if(node->right!=NULL) input.push(node->right); } while(!output.empty()) { node=output.top(); output.pop(); ret.push_back(node->val); } return ret; } };
相关文章推荐
- leetcode_c++:栈: Binary Tree Postorder Traversal(145)
- Binary Tree Postorder Traversal - LeetCode 145
- 【LeetCode-145】Binary Tree Postorder Traversal(C++)
- Leetcode 145 Binary Tree Postorder Traversal
- LeetCode 145: Binary Tree Postorder Traversal(二叉树的后序遍历,迭代法)
- Leetcode_145_Binary Tree Postorder Traversal
- LeetCode 145 Binary Tree Postorder Traversal
- leetcode——145——Binary Tree Postorder Traversal
- [leetcode 145] Binary Tree Postorder Traversal (待完善)
- LeetCode_145 Binary Tree Postorder Traversal
- LeetCode145—Binary Tree Postorder Traversal
- 【leetcode】【145】Binary Tree Postorder Traversal
- 【LeetCode-面试算法经典-Java实现】【145-Binary Tree Postorder Traversal(二叉树非递归后序遍历)】
- LeetCode 145 Binary Tree Postorder Traversal
- LeetCode #145 - Binary Tree Postorder Traversal - Hard
- leetcode(145):Binary Tree Postorder Traversal
- [LeetCode]题解(python):145-Binary Tree Postorder Traversal
- LeetCode 145:Binary Tree Postorder Traversal(后序遍历)
- LeetCode 145:Binary Tree Postorder Traversal
- LeetCode: Binary Tree Postorder Traversal [145]