Binary Tree Postorder Traversal
来源:互联网 发布:java web网站开发模板 编辑:程序博客网 时间:2024/06/09 13:49
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?
这道题目最简单的方法是用recursive 做,其次是用 stack+queue, 最难想清楚的是stack。当然写过了 也就不觉得难了。
/** * 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) { List<Integer> res = new ArrayList<Integer>(); if (root == null) { return res; } Stack<TreeNode> st = new Stack<TreeNode>(); TreeNode pre = null;//用来判断 cur 与 pop 出的节点,或stack 中临近节点的关系 st.push(root); while (!st.empty()) { // cur always equals to st.peet(); TreeNode cur = st.peek(); // 说明只放了root, 或者pre 是cur 在stack 下面的元素,即说明还是在遍历左右子树的过程 if (pre == null || pre.left == cur || pre.right == cur) { if (cur.left != null) { st.push(cur.left); } else if (cur.right != null) { st.push(cur.right); } else { res.add(cur.val); st.pop(); } } else if (pre == cur.left) { //则要判断cur 是否还有右节点,有的话,右节点入栈 if (cur.right != null) { st.push(cur.right); } else { res.add(cur.val); st.pop(); } } else {//即pre ==cur.right,此时说明 cur 的左右节点都已经遍历 res.add(cur.val); st.pop(); } pre = cur; } 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
- lazarus1.2.4创建编译WINCE程序
- python property属性
- 程序员的十大烦恼
- iOS获取各种文件的目录路径的方法
- IP地址分类与识别错误
- Binary Tree Postorder Traversal
- crawler4j打包与配置
- poj 1511 Dijkstra的另一种用法---求其他点到源点的最短路
- iOS开发-植入广告(iAd, Admob实例)
- [LeetCode]Scramble String
- iOS开发 - 应用国际化开发
- poj 1091——跳蚤
- Codeforces441C_Valera and Tubes(暴力)
- iOS开发-键盘样式风格有关设置