非递归实现二叉树后序遍历
/* 145. 二叉树的后序遍历* 题目描述:非递归实现二叉树中序遍历* 解题思路:* */
public class BinaryTreePostorder {public static void main(String[] args) {TreeNode root = new TreeNode(1);root.left=new TreeNode(2);root.right=new TreeNode(3);BinaryTreePostorderSolution1 solution = new BinaryTreePostorderSolution1();List list = solution.postorderTraversal(root);Iterator<Integer> iterator = list.iterator();while(iterator.hasNext()) {System.out.println(iterator.next());}}
}class BinaryTreePostorderSolution1 {/* 宽度优先搜索:* */public List<Integer> postorderTraversal(TreeNode root) {Stack<TreeNode> stack1 = new Stack<TreeNode>();Stack<TreeNode> stack2 = new Stack<TreeNode>();List<Integer> list = new ArrayList<Integer>();stack1.push(root);while(!stack1.isEmpty()) {TreeNode node = stack1.pop();stack2.push(node);if(node.left!=null) stack1.push(node.left);if(node.right!=null) stack1.push(node.right);}while(!stack2.isEmpty()) {list.add(stack2.pop().val);}return list;}
}