Binary Tree Postorder Traversal
来源:互联网 发布:七匣子淘宝 编辑:程序博客网 时间:2024/06/11 11:45
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1 \ 2 / 3return [3,2,1].
递归实现:
public List<Integer> postorderTraversal(TreeNode root) {List<Integer> result=new ArrayList<Integer>();if(root==null)return result;result.addAll(postorderTraversal(root.left));result.addAll(postorderTraversal(root.right));result.add(root.val);return result;}
循环实现:
public List<Integer> postorderTraversal(TreeNode root) {ArrayList<Integer> result = new ArrayList<Integer>();Stack<TreeNode> stack = new Stack<TreeNode>();TreeNode prev = null; // previously traversed nodeTreeNode curr = root;if (root == null) return result;stack.push(root);while (!stack.empty()) {curr = stack.peek();if (prev == null || prev.left == curr || prev.right == curr) { // traverse down the treeif (curr.left != null) stack.push(curr.left);else if (curr.right != null)stack.push(curr.right);} else if (curr.left == prev) { // traverse up the tree from the leftif (curr.right != null) stack.push(curr.right);} else { // traverse up the tree from the rightresult.add(curr.val);stack.pop();}prev = curr;}return result;}
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
- php 命令执行系列
- POJ 2014:Flow Layout 模拟水题
- 每日20行之3~~~ThreadPool之RegisterWaitForSingleObject 自动定时执行(可循环)
- HDU1863:畅通工程【Kruskal & Prim】
- HDOJ--1863--畅通工程
- Binary Tree Postorder Traversal
- Android-自定义Dialog
- MySQL学习总结1
- java学习笔记-------对卡片布局管理器的深入理解
- dpkg命令
- 新blog
- JTextArea设置滚动条
- poj3320
- SQL truncate 、delete与drop区别