Clear Java DFS Solution using stack


  • 0
    L
    public class Solution {
        public List<Integer> preorderTraversal(TreeNode root) {
            List<Integer> res = new ArrayList<>();
            if(root == null) return res;
            
            Stack<TreeNode> stack = new Stack<>();
            stack.push(root);
            while(!stack.isEmpty()) {
                TreeNode p = stack.pop();
                res.add(p.val);
                if(p.right != null) stack.push(p.right);
                if(p.left != null) stack.push(p.left);
            }
            
            return res;
        }
    }
    

Log in to reply
 

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