This method will cost O(n) time with no extra space. The space is assigned by system(which could be O(1) or O(h), h is the height of the tree).
1 2 3 4 5 6 7 8 9 10 11 12 13 14
public ArrayList<Integer> preorderTraversal(TreeNode root){ ArrayList<Integer> result = new ArrayList<Integer>(); helper(root, result); return result; }
Use a stack to store the nodes. Pay attention to the order of storing. We store the right subtree node before the left one, so that we can get the preorder nodes when pop from the stack. This method will cost O(n) time with O(h) extra space for the stack.