递归
public List<Integer> preorderTraversal(TreeNode root) {List<Integer> list = new ArrayList<>();traversal(root, list);return list;}public void traversal(TreeNode t, List<Integer> list) {if (t == null) {return;}list.add(t.val);traversal(t.left, list);traversal(t.right, list);}
迭代(不断走向左子树)
public List<Integer> preorderTraversal(TreeNode root) {List<Integer> list = new ArrayList<>();Deque<TreeNode> stack = new LinkedList<>();TreeNode t = root;while (!stack.isEmpty() || t != null) {if (t != null) {list.add(t.val);stack.push(t);t = t.left;} else {t = stack.pop();t = t.right;}}return list;}
迭代(先放右子树,再放左子树)
public List<Integer> preorderTraversal(TreeNode root) {List<Integer> list = new ArrayList<>();Deque<TreeNode> stack = new LinkedList<>();if(root==null)return list;TreeNode t = root;stack.push(t);while (!stack.isEmpty()) {t = stack.pop();list.add(t.val);if (t.right != null) {stack.push(t.right);}if (t.left != null) {stack.push(t.left);}}return list;}