使用迭代法对二叉树进行后序遍历——Leetcode系列(六)
来源:互联网 发布:琅琊榜细节 知乎 编辑:程序博客网 时间:2024/06/05 01:09
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?
My Answer
<span style="font-size:14px;">/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public List<Integer> postorderTraversal(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); List<Integer> list = new ArrayList<Integer>(); if(root == null){ return list; } stack.push(root); while(!stack.empty()){ TreeNode top = stack.pop(); if(top.left == null && top.right == null){ list.add(top.val); }else{ stack.push(new TreeNode(top.val)); if(top.right != null){ stack.push(top.right); } if(top.left != null){ stack.push(top.left); } } } return list; }}</span>
题目来源:https://oj.leetcode.com/problems/binary-tree-postorder-traversal/
0 0
- 使用迭代法对二叉树进行后序遍历——Leetcode系列(六)
- 使用迭代法对二叉树进行前序遍历——Leetcode系列(七)
- LeetCode 145: Binary Tree Postorder Traversal(二叉树的后序遍历,迭代法)
- LeetCode基础--二叉树--后序遍历
- 二叉树的后序遍历(leetcode 145)
- 创建二叉树,并对其进行 先序、中序、后序遍历
- 用递归方法对二叉树进行先序、中序和后序遍历
- 用递归方法对二叉树进行先序、中序和后序遍历
- 用递归方法对二叉树进行先序、中序和后序遍历
- 对二叉树进行前序、中序、后序遍历
- (1)建立二叉树的二叉链表。 (2)写出对用二叉链表存储的二叉树进行先序、中序和后序遍历的递归和非递归算法。 (3)写出对用二叉链表存储的二叉树进行层次遍历算法。 (4)求二叉树的所有叶子及结点总数。
- 二叉树系列——层序遍历二叉树
- 用栈进行二叉树的后序遍历
- 使用快速排序算法对列表进行排序——Leetcode系列(四)
- 使用插入排序算法对列表进行排序——Leetcode系列(五)
- 用栈对二叉树进行中序遍历
- 利用栈对二叉树进行遍历
- 六、树和二叉树--(2)二叉树的先序遍历、中序遍历、后序遍历
- 发送TCP数据包
- 搜狐云景客户端工具评测之WordPress的搭建
- google开源protobuf
- vc中release和debug的区别
- JAVA 通过HtmlParser获取指定的tag
- 使用迭代法对二叉树进行后序遍历——Leetcode系列(六)
- 网站建设10个最好的响应的HTML5滑块插件
- 互联网思维:高大上难接地气
- UVa 657 - The die is cast
- U-boot引导流程分析二
- C++的基本应用
- linux内核源代码的C语言代码
- caperjs操作cookie
- 写驱动时交叉编译之makefile编写模板(tiny6410)