Binary Tree Postorder Traversal
来源:互联网 发布:windows app store 编辑:程序博客网 时间:2024/06/06 16:29
参考了论坛大神的经典解法,以最简单的pre-order遍历为基础进行post-order遍历。pre-order遍历的代码参见Binary Tree Preorder Traversal。
基本思路是在pre-order中,遍历顺序是root-left-right,这样可以用一个栈进行简单模拟,因为pre-order是典型的尾递归。
但post-order则不同,由于是left-right-root的顺序,对root的访问是放在最后的。本题解法的关键是对pre-order中遍历顺序的一个灵活改变,变为root-right-left,这样仍然是一种尾递归的形式,但是这样顺序正好是post-order的逆序!!!,所以在输出时只要逆序输出成为了post-order的遍历顺序。
/** * 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> res; if(!root) { return res; } stack<TreeNode*> stk; TreeNode* tmp=NULL; stk.push(root); while(!stk.empty()) { tmp=stk.top(); stk.pop(); res.push_back(tmp->val); if(tmp->left) { stk.push(tmp->left); } if(tmp->right) { stk.push(tmp->right); } } return vector<int>(res.rbegin(),res.rend()); }};
/** * 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> res; if(!root) { return res; } stack<TreeNode*> stk; TreeNode* lastPop=root; stk.push(root); while(!stk.empty()) { TreeNode* tmp=stk.top(); if((tmp->left!=NULL)&&(lastPop!=tmp->left)&&(lastPop!=tmp->right)) { stk.push(tmp->left); } else if((tmp->right!=NULL)&&(lastPop!=tmp->right)&&(tmp->left==NULL||tmp->left==lastPop)) { stk.push(tmp->right); } else { stk.pop(); res.push_back(tmp->val); lastPop=tmp; } } return res; }};
0 0
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- 慢牛股票-基于Sencha touch+Cordova的股票类APP
- 大端小端
- 网卡驱动---网卡及网络知识 储备
- 多维动态数组定义及应用
- Apache配置301跳转和开启.htaccess的方法
- Binary Tree Postorder Traversal
- HTML5 Access-Control-Allow-Origin解决跨域问题
- 导弹拦截-动态规划
- 继承方式
- IOS引导界面
- WoSign正式成为FIDO联盟Sponsor级别成员单位
- 网游避免事务与回滚
- 注胶隔热型材加工过程中常见问题、解析及处理系列阐述
- SQL基础(八)--SELECT