Binary Tree Preorder Traversal

 Given the root of a binary tree, return the preorder traversal of its nodes' values.


 


Example 1:


Input: root = [1,null,2,3]


Output: [1,2,3]


Explanation:



Example 2:


Input: root = [1,2,3,4,5,null,8,null,null,6,7,9]


Output: [1,2,4,5,6,7,3,8,9]


Explanation:



Example 3:


Input: root = []


Output: []


Example 4:


Input: root = [1]


Output: [1]

 Approach 1: Recursive (Simple)

🔹 Steps:

  1. Visit the current node → add value to result

  2. Recursively traverse the left subtree

  3. Recursively traverse the right subtree

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
 class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        preorder(root, result);
        return result;
    }

    private void preorder(TreeNode node, List<Integer> res) {
        if (node == null) return;

        res.add(node.val);              // Visit root
        preorder(node.left, res);       // Left subtree
        preorder(node.right, res);      // Right subtree
    }
}



Java Code (Iterative):


class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) return result;

        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);

        while (!stack.isEmpty()) {
            TreeNode current = stack.pop();
            result.add(current.val); // Visit node

            if (current.right != null) {
                stack.push(current.right);  // Right child
            }
            if (current.left != null) {
                stack.push(current.left);   // Left child
            }
        }
        return result;
    }
}

Comments

Popular posts from this blog

Increasing Triplet Subsequence

Number of Zero-Filled Subarrays

What is Encryption and Decryption?