用递归和迭代求Pre-Order的经典题,什么时候要把In-Order, Post-Order, Level-Order 的遍历都写一遍,因为太经典了,最好能直接背下来。
package Level3; import java.util.ArrayList; import java.util.Stack; /** * Binary Tree Preorder Traversal * * Given a binary tree, return the preorder traversal of its nodes' values. For example: Given binary tree {1,#,2,3}, 1 \ 2 / 3 return [1,2,3]. Note: Recursive solution is trivial, could you do it iteratively? */ import Utility.TreeNode; public class S128 { public static void main(String[] args) { TreeNode root = new TreeNode(1); TreeNode n1 = new TreeNode(2); root.right = n1; System.out.println(preorderTraversal(root)); System.out.println(iter(root)); } public static ArrayList<Integer> preorderTraversal(TreeNode root) { ArrayList<Integer> ret = new ArrayList<Integer>(); rec(root, ret); return ret; } public static void rec(TreeNode root, ArrayList<Integer> ret){ if(root == null){ return; } ret.add(root.val); rec(root.left, ret); rec(root.right, ret); } // 迭代法 public static ArrayList<Integer> iter(TreeNode root) { ArrayList<Integer> ret = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); if(root == null){ return ret; } stack.push(root); TreeNode cur = null; while(!stack.isEmpty()){ cur = stack.peek(); // 保存栈顶元素 ret.add(cur.val); stack.pop(); // 要先放右元素再放左元素,这样才能在pop时先pop左元素再pop右元素 if(cur.right != null){ stack.push(cur.right); } if(cur.left != null){ stack.push(cur.left); } } return ret; } }
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public ArrayList<Integer> preorderTraversal(TreeNode root) { ArrayList<Integer> ret = new ArrayList<Integer>(); if(root == null){ return ret; } Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); while(!stack.isEmpty()){ TreeNode cur = stack.pop(); ret.add(cur.val); if(cur.right != null) stack.push(cur.right); if(cur.left != null) stack.push(cur.left); } return ret; } }