class Solution { public List<Integer> preorderTraversal(TreeNode root) { Stack<TreeNode> stack=new Stack<TreeNode>(); List<Integer> res=new ArrayList<Integer>(); while(root!=null||!stack.isEmpty()) { while(root!=null) { res.add(root.val); stack.push(root); root=root.left; } root=stack.pop().right; } return res; } }
class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> res=new ArrayList<Integer>(); TreeNode cur=root, pre=null; while(cur!=null) { if(cur.left==null) { res.add(cur.val); cur=cur.right; } else { pre=cur.left; while(pre.right!=null&&pre.right!=cur) pre=pre.right; if(pre.right==null) { res.add(cur.val); pre.right=cur; cur=cur.left; } else { pre.right=null; cur=cur.right; } } } return res; } }