Clear Java DFS Solution using stack

  • 0
    public class Solution {
        public List<Integer> preorderTraversal(TreeNode root) {
            List<Integer> res = new ArrayList<>();
            if(root == null) return res;
            Stack<TreeNode> stack = new Stack<>();
            while(!stack.isEmpty()) {
                TreeNode p = stack.pop();
                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.