leetcode:Binary Tree Postorder Traversal
2016-03-06 13:30
471 查看
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?
Subscribe to see which companies asked this question
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?
Subscribe to see which companies asked this question
/** * 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 { private: void pushNodeToStack(TreeNode* root, stack<TreeNode*> &auxStack) { TreeNode* curNode = root; while (curNode->left != NULL || curNode->right != NULL) { if (curNode->right) auxStack.push(curNode->right); if (curNode->left) auxStack.push(curNode->left); curNode = auxStack.top(); } return; } public: vector<int> postorderTraversal(TreeNode* root) { vector<int> retVtr; if (root == NULL) return retVtr; stack<TreeNode *> auxStack; auxStack.push(root); pushNodeToStack(root, auxStack); while (auxStack.size() > 0) { TreeNode *preNode = NULL; while (auxStack.size() > 0 && (preNode == auxStack.top()->left || preNode == auxStack.top()->right)) { TreeNode *curNode = auxStack.top(); preNode = curNode; auxStack.pop(); retVtr.push_back(curNode->val); } if (auxStack.size() > 0) pushNodeToStack(auxStack.top(), auxStack); } return retVtr; } };
相关文章推荐
- ssh框架结构分析
- java.lang.NoClassDefFoundError: org/mybatis/generator/exception/InvalidConfigurationException
- AdaBoost从原理到实现
- 构建之法阅读笔记01
- 构建之法阅读笔记01
- 构建之法
- Python执行系统命令的方法 os.system(),os.popen(),commands
- python 抓取百度音乐
- leetcode之atoi() in java
- N皇后问题
- react native 样式初学~(一)
- iOS开发:JavaScriptCore.framework的简单使用--JS与OC的交互篇
- N皇后问题
- 基于Python实现一个简单的银行转账操作
- 未来10年,中国最具投资价值的17个新兴产业
- 4321.com域名中介商倒闭
- 未来10年,中国最具投资价值的17个新兴产业
- 第一个单片机程序
- java 数据结构 常见的排序算法
- JS思维之路菜鸟也能有大能量(2)--模拟数组合并concat