【LeetCode从零单刷】Binary Tree Postorder Traversal
来源:互联网 发布:零基础学云计算 编辑:程序博客网 时间:2024/06/02 05:50
题目:
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]
.
解答:
二叉树的非递归版本后续遍历。二叉树各种遍历的非递归版本难度不同,大致是:前序 > 中序 > 后序。
后序遍历的实现其他思路可以参考这里:传送门
这里介绍一种简单的方法。因为前序是最容易实现的,我们可不可以将后序遍历中的 “左右根”,看成是 “根右左” 的逆序版本?而 “根右左” 是否和前序遍历有着相同的实现原理?答案是肯定的。
/** * 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) { stack<TreeNode*> postorder; vector<int> ans; ans.clear(); if(root == NULL) return ans; TreeNode* tmp = root; postorder.push(root); while(!postorder.empty()){ // 区分加入vector与加入stack的不同 ans.push_back(postorder.top()->val); tmp = postorder.top(); postorder.pop(); // 与前序遍历相同,最后reverse if(tmp->left) postorder.push(tmp->left); if(tmp->right) postorder.push(tmp->right); } reverse(ans.begin(), ans.end()); return ans; }};
0 0
- 【LeetCode从零单刷】Binary Tree Postorder Traversal
- LeetCode Binary Tree Postorder Traversal
- LeetCode:Binary Tree Postorder Traversal
- Leetcode: Binary Tree Postorder Traversal
- Leetcode: Binary Tree Postorder Traversal
- LeetCode:Binary Tree Postorder Traversal
- Leetcode Binary Tree Postorder Traversal
- [LeetCode]Binary Tree Postorder Traversal
- [LeetCode] Binary Tree Postorder Traversal
- leetcode Binary Tree Postorder Traversal
- 【LeetCode】Binary Tree Postorder Traversal
- LeetCode | Binary Tree Postorder Traversal
- Leetcode: Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal - LeetCode
- LeetCode - Binary Tree Postorder Traversal
- [LeetCode]Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal -- LeetCode
- [LeetCode]Binary Tree Postorder Traversal
- 第三周—项目4 顺序表应用
- Linux查看和结束进程命令详解
- Theme.AppCompat.Light.NoActionBar - 解决新版ADT创建项目时出现appcompat_v7并报错
- 【剑指Offer】重建二叉树
- 路由子系统——路由查找(留坑)
- 【LeetCode从零单刷】Binary Tree Postorder Traversal
- Oracle GoldenGate 系列:Extract 进程的恢复原理
- 路哟子系统——高级路由(留坑)
- 【矩阵快速幂】 HDOJ 5434 Peace small elephant
- Speed Limit-2017
- c# DateTime.Now 大写英文月份
- Eclipse常用插件在线安装
- 《AndroidStudio每日一贴》9. 如何使用导航栏快速切换项目中的视图?
- hdoj 3308 LCIS 【线段树单点更新 + 区间合并】【求解最长递增序列 的长度】