首页 > 代码库 > [LeetCode]145 Binary Tree Postorder Traversal
[LeetCode]145 Binary Tree Postorder Traversal
https://oj.leetcode.com/problems/binary-tree-postorder-traversal/
http://blog.csdn.net/ljphhj/article/details/21369053
/** * 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) { // Solution A // List<Integer> toReturn = new ArrayList<>(); // postorderTraversal_recursively(root, toReturn); // return toReturn; // Solution B return postorderTraversal_iteratively(root); } /////////////////////// // // Solution B: Iteratively // private List<Integer> postorderTraversal_iteratively(TreeNode root) { List<Integer> toReturn = new ArrayList<>(); if (root == null) return toReturn; // Define a stack. Stack<CheckedNode> stack = new Stack<>(); stack.push(new CheckedNode(root, false)); while (!stack.empty()) { CheckedNode checkednode = stack.pop(); if (checkednode.checked || // The node has been checked (checkednode.node.left == null && checkednode.node.right == null)) // A leaf node { // If the node has checked // Just add its value toReturn.add(checkednode.node.val); } else { // Checking this node. // Push it back, push its right, push its left checkednode.checked = true; stack.push(checkednode); if (checkednode.node.right != null) { stack.push(new CheckedNode(checkednode.node.right, false)); } if (checkednode.node.left != null) { stack.push(new CheckedNode(checkednode.node.left, false)); } } } return toReturn; } private static class CheckedNode { TreeNode node; boolean checked; CheckedNode(TreeNode node, boolean checked) { this.node = node; this.checked = checked; } } /////////////////////// // // Solution A: Recursively // private void postorderTraversal_recursively(TreeNode node, List<Integer> result) { if (node == null) return; postorderTraversal_recursively(node.left, result); postorderTraversal_recursively(node.right, result); result.add(node.val); } }
[LeetCode]145 Binary Tree Postorder Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。