classSolution{List<Integer> res;publicList<Integer>preorderTraversal(TreeNode root){
res =newArrayList();preorder(root);return res;}privatevoidpreorder(TreeNode node){if(node ==null)return;
res.add(node.val);preorder(node.left);preorder(node.right);}}
Iterative
classSolution{publicList<Integer>preorderTraversal(TreeNode root){List<Integer> res =newArrayList();Stack<TreeNode> stack =newStack();TreeNode cur = root;// Traverse the whole treewhile(cur !=null||!stack.isEmpty()){// Go to the left whenever possiblewhile(cur !=null){
res.add(cur.val);// Add the parent node
stack.push(cur);// Memorize the parent node
cur = cur.left;// Move to the deeper left}// Reach the null, pop the parent
cur = stack.pop();// Go to the right
cur = cur.right;}return res;}}