递归
public class Solution { public ArrayListpreorderTraversal(TreeNode root) { ArrayList res = new ArrayList (); traversal(root, res); return res; } public void traversal(TreeNode root, ArrayList res) { if (root == null) { return; } res.add(root.val); traversal(root.left, res); traversal(root.right, res); }}
非递归
public class Solution { public ArrayListpreorderTraversal(TreeNode root) { Stack stack = new Stack (); ArrayList preorder = new ArrayList (); if (root == null) { return preorder; } stack.push(root); while (!stack.isEmpty()) { TreeNode node = stack.pop(); preorder.add(node.val); if (node.right != null) { stack.push(node.right); } if (node.left != null) { stack.push(node.left); } } return preorder; }}
divide and conquer
public ArrayListpreorderTraversal(TreeNode root) { ArrayList res= new ArrayList (); if (root == null) { return res; } ArrayList left = preorderTraversal(root.left); ArrayList right = preorderTraversal(root.right); res.add(root.val); res.addAll(left); res.addAll(right); return res; }