递归
public class Solution { public ArrayList<Integer> preorderTraversal(TreeNode root) { ArrayList<Integer> res = new ArrayList<Integer>(); traversal(root, res); return res; } public void traversal(TreeNode root, ArrayList<Integer> res) { if (root == null) { return; } res.add(root.val); traversal(root.left, res); traversal(root.right, res); } }
非递归
public class Solution { public ArrayList<Integer> preorderTraversal(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); ArrayList<Integer> preorder = new ArrayList<Integer>(); 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 ArrayList<Integer> preorderTraversal(TreeNode root) { ArrayList<Integer> res= new ArrayList<Integer>(); if (root == null) { return res; } ArrayList<Integer> left = preorderTraversal(root.left); ArrayList<Integer> right = preorderTraversal(root.right); res.add(root.val); res.addAll(left); res.addAll(right); return res; }
时间: 2024-10-24 22:20:10