[LeetCode]145 二叉树后序遍历
来源:互联网 发布:淘宝刷单兼职91lingla 编辑:程序博客网 时间:2024/05/28 05:13
Binary Tree Postorder Traversal(二叉树后序遍历)
【难度:Medium】
Given a binary tree, return the postorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3},
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
使用迭代而不是递归的方法后序遍历二叉树
解题思路
整体思路与LeetCode 94题和144题一致,但在后序遍历这里采取的是先走根节点,再走右子树,再走左子树,最后将结果顺序反转来得到后序遍历的答案,因为这样比较方便。
c++代码如下:
//迭代方法/** * 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) { vector<int> v; stack<TreeNode*> s; TreeNode* cur = root; while (cur || !s.empty()) { if (cur) { s.push(cur); v.push_back(cur->val); cur = cur->right; } else { cur = s.top()->left; s.pop(); } } reverse(v.begin(),v.end()); return v; }};
//递归方法/** * 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) { vector<int> v; if (!root) return v; vector<int> left = postorderTraversal(root->left); if (!left.empty()) { for (auto i:left) v.push_back(i); } vector<int> right = postorderTraversal(root->right); if (!right.empty()) { for (auto i:right) v.push_back(i); } v.push_back(root->val); return v; }};
0 0
- [LeetCode]145 二叉树后序遍历
- LeetCode 145 Binary Tree Postorder Traversal(二叉树后序遍历)
- [leetcode]二叉树先序遍历
- [leetcode]二叉树中序遍历
- leetcode二叉树遍历
- [leetcode]二叉树遍历
- 二叉树遍历LeetCode#144 #94 #145 (前中后序遍历)
- [LeetCode]144 二叉树先序遍历
- [LeetCode]94 二叉树中序遍历
- LeetCode之二叉树中序迭代遍历
- Leetcode: Binary Tree Postorder Traversal(二叉树后序遍历)
- Leetcode Binary Tree Postorder Traversal 二叉树后序遍历
- LeetCode 145. Binary Tree Postorder Traversal(二叉树后序遍历)
- 145.leetcode Binary Tree Postorder Traversal(easy)[二叉树后序遍历]
- [leetcode-二叉树后序遍历]--145. Binary Tree Postorder Traversal
- [Leetcode] 二叉树的遍历(#94,#144,#145 )
- 二叉树的后序遍历(leetcode 145)
- leetcode之二叉树类之二叉树遍历系列-----94/144/145/102/107/103
- CakePHP 3.2 数据库访问和ORM篇
- mongodb集群搭建
- 连连看完善
- 上机题目(初级)- 下雪球(Java)
- Python IDLE或Python Shell不支持中文编码的解决方案
- [LeetCode]145 二叉树后序遍历
- ELK(六)ElasticSearch索引
- gcc/g++ 动态 静态 链接库 so
- Linux http post 请求 实例
- SQL Server 2008 : Invoke or BeginInvoke cannot be called on a control until the window handle has ..
- A*寻路算法
- dl dt dd 标签的用法(二)
- 第一次课设完成后的闲谈——学生宿舍管理系统
- LeetCode : Regular Expression Matching [java]