Java AC solution


  • 0
    F
    public List<Integer> preorderTraversal(TreeNode root) {
            List<Integer> res = new ArrayList<Integer>();
            Stack<TreeNode> s = new Stack();
            TreeNode n = root;
            while (n != null) {
                res.add(n.val);
                if(n.right != null) {
                    s.push(n.right);
                }
                 if (n.left != null) {
                    s.push(n.left);
                }
                n = s.empty() ? null : s.pop();
            }
            return res;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.