(TreeNode root)
| 1 | class Solution { |
| 2 | public List<Integer> preorderTraversal(TreeNode root) { |
| 3 | Stack<TreeNode> stack = new Stack<>(); |
| 4 | List<Integer> preOrder = new ArrayList<Integer>(); |
| 5 | if(root==null) return preOrder; |
| 6 | stack.push(root); |
| 7 | while(!stack.isEmpty()) |
| 8 | { |
| 9 | root=stack.pop(); |
| 10 | preOrder.add(root.val); |
| 11 | if(root.right!=null) |
| 12 | { |
| 13 | stack.push(root.right); |
| 14 | } |
| 15 | if(root.left!=null) |
| 16 | { |
| 17 | stack.push(root.left); |
| 18 | } |
| 19 | } |
| 20 | return preOrder; |
| 21 | } |
| 22 | } |