【Leetcode】Binary Tree Postorder Traversal
来源:互联网 发布:马步芳 知乎 编辑:程序博客网 时间:2024/06/04 23:27
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]
.
后续的定义:后序遍历首先遍历左子树,然后遍历右子树,最后访问根结点,在遍历左、右子树时,仍然先遍历左子树,然后遍历右子树,最后遍历根结点。
思路:后续遍历的方式我们也可以巧用stack,每次我们把root都先放进stack中,直到到左节点的最底层,然后最底层左节点作为第一个pop出来的元素(此时必然既没有left也没有right,)然后此时可以把值加进去。
public class Solution {ArrayList<Integer> list = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>();public ArrayList<Integer> postorderTraversal(TreeNode root) { if (root == null) return list; stack.push(root);//先把根节点放进最底层的stack while (stack.size() != 0){ TreeNode top = stack.peek();//栈中最上面的node先拿出来 if (top.left == null && top.right == null){//到最底层了,再也没有下面了,就加进list list.add(top.val); stack.pop();//一定注意把这个node从stack中拿出来 } if (top.left != null){//把做节点放进stack中 stack.push(top.left); top.left = null; continue; } if (top.right != null){//把右节点放进去 stack.push(top.right); top.right = null; continue; } } return list; }}
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
- 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
- 【LeetCode】Binary Tree Postorder Traversal
- ch7.JavaBean
- matlab提供的变换函数
- Web开发之分页算法,N(N>=3)种解决方案
- VC使用CRT调试功能检测内存泄漏
- Ubuntu 12.04 安装openjdk7以及jre
- 【Leetcode】Binary Tree Postorder Traversal
- mysql 索引简介
- SICP-《计算机程序的构造和解释》之习题分析与收获——练习1.29
- linux redhat、suse、debain、ubuntu、fedora各版本区别(一)
- ceph存储 Centos下建立RPM包中spec文件编写说明书
- linux进程间通信--共享内存
- 使用指针输出数组的任一行任一列的元素
- C++对象模型 第五章 构造、析构、拷贝语意学
- linux suse、debain、ubuntu、fedora、centos各版本区别(二)