标签:
1 Given a binary tree, return the postorder traversal of its nodes‘ values. 2 3 For example: 4 Given binary tree {1,#,2,3}, 5 1 6 7 2 8 / 9 3 10 return [3,2,1]. 11 12 Note: Recursive solution is trivial, could you do it iteratively?
Recursive:
/** * 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> list = new ArrayList<Integer>(); if(root == null){ return list; } list.addAll(postorderTraversal(root.left)); list.addAll(postorderTraversal(root.right)); list.add(root.val); return list; } }
Iterative:
/** * 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> list = new ArrayList<Integer>(); if(root == null){ return list; } Stack<TreeNode> stack = new Stack<TreeNode>(); ArrayList<TreeNode> visited = new ArrayList<TreeNode>(); stack.push(root); while(root != null || !stack.isEmpty()){ if(root.left != null && !visited.contains(root.left)){ stack.push(root.left); root=root.left; } else if(root.right != null && !visited.contains(root.right)){ stack.push(root.right); root = root.right; } else{ visited.add(root); list.add(stack.pop().val); if(!stack.isEmpty()){ root = stack.peek(); } else { root=null; } } } return list; } }
LeetCode-Binary Tree Postorder Traversal
标签:
原文地址:http://www.cnblogs.com/incrediblechangshuo/p/4341256.html