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]
Follow up: Recursive solution is trivial, could you do it iteratively?
Method One: recursive
The idea is very simple, root around
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public void preorderTraversal(TreeNode root) { if(root==null) return ; System.out.print(root.val+' '); preorderTraversal(root.left); preorderTraversal(root.right); } }
Method Two: Iteration
Iterative Solution can all use recursion problem with recursion is nothing more than the use of the system function stack, if they apply for the data structure to replace the function stack, can achieve the same functionality.
Preorder traversal around roots, root added to the stack and then pop, pop up each time, the right and left pop-up node subtree is added to ensure that the order of about pop roots.
/** * 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) { if(root==null) return null; if(root!=null) { Stack<TreeNode> stack=new Stack<TreeNode>(); List<Integer> list=new ArrayList<Integer>(); stack.add(root); while (!stack.isEmpty()){ root=stack.pop(); list.add(root.val); if(root.right!=null) { stack.add(root.right); } if(root.left!=null){ stack.add(root.left); } } } return list; } }