[LeetCode] Binary Tree Postorder Traversal [42]
2014-07-31 20:46
309 查看
题目
Binary Tree Postorder Traversal
Total Accepted: 23797 TotalSubmissions: 76975My Submissions
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?
原题链接
解题思路
于中序遍历类似,使用stack。不过此题注意需要使用一个额外的指针来保证其左右孩子都已经被访问过。实现代码
vector<int> postorderTraversal(TreeNode *root) { vector<int> ret; if (root == NULL) return ret; TreeNode *pNode = NULL; TreeNode *pLast = NULL; std::stack<TreeNode *> s; s.push(root); while (!s.empty()) { pNode = s.top(); if ( (pNode->left == NULL && pNode->right == NULL) || ((pLast!=NULL)&& (pNode->left == pLast || pNode->right == pLast))) { ret.push_back(pNode->val); pLast = pNode; s.pop(); } else { if (pNode->right != NULL) s.push(pNode->right); if (pNode->left != NULL) s.push(pNode->left); } } return ret; }
如果你觉得本篇对你有收获,请帮顶。
另外,我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.
你可以搜索公众号:swalge 或者扫描下方二维码关注我
(转载文章请注明出处: http://blog.csdn.net/swagle/article/details/38323117 )
相关文章推荐
- LeetCode 145 Binary Tree Postorder Traversal
- leetcode--Construct Binary Tree from Inorder and Postorder Traversal
- leetcode || 145、Binary Tree Postorder Traversal
- LeetCode - 106. Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode 145 Binary Tree Postorder Traversal(二叉树的后续遍历)+(二叉树、迭代)
- LeetCode-Binary Tree Postorder Traversal
- 【LeetCode】Construct Binary Tree from Inorder and Postorder Traversal
- 73_leetcode_Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]145 Binary Tree Postorder Traversal
- [LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode:Binary Tree Postorder Traversal
- leetcode - Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode oj java Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode(106) Construct Binary Tree from Inorder and Postorder Traversal
- functionclass[LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
- Binary Tree Postorder Traversal (leetcode)
- [LeetCode] 020: Construct Binary Tree from Inorder and Postorder Traversal
- leetcode--Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode: Binary Tree Postorder Traversal