144. Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values.
Example:
Input:[1,null,2,3]
1 \ 2 / 3 Output:[1,2,3]
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> res = new ArrayList(); Stack<TreeNode> s = new Stack<>(); if(root != null) s.push(root); while(!s.isEmpty()){ TreeNode p = s.pop(); res.add(p.val); //注意stack是last in first out,所以先push right if(p.right != null) s.push(p.right); if(p.left != null) s.push(p.left); } return res; } }