My Java easy DFS solution


  • 1
    Z

    Using DFS directly by poping root node then, pushing right node, then left node. You will easily get your answer!

    My code:
    
    
    
    public class Solution {
        public List<Integer> preorderTraversal(TreeNode root) {
            
            Stack<TreeNode> stack = new Stack<TreeNode>();
            List<Integer> list = new ArrayList<Integer>();
            
            if (root == null) return list;
            
            // DFS init
            stack.push(root);
            while (!stack.isEmpty()) {
                TreeNode cur = stack.pop();
                list.add(cur.val);
                if (cur.right != null) {
                    stack.push(cur.right);
                }
                if (cur.left != null) {
                    stack.push(cur.left);
                }
            }
            return list;
        }
    }
    

Log in to reply
 

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