Tree: Preorder Traversal

  • + 0 comments

    My Java 8 solutions

    Recursive approach

    public static void preOrder(Node root) {
        if (root == null) return;
    
        System.out.print(root.data + " ");
        preOrder(root.left);
        preOrder(root.right);
    }
    

    Iterative approach

    public static void preOrder(Node root) {
        if (root == null) return;
    
        Stack<Node> stack = new Stack<>();
        stack.push(root);
    
        while (!stack.isEmpty()) {
            Node current = stack.pop();
            System.out.print(current.data + " ");
    				
            if (current.right != null) {
                stack.push(current.right);
            }
    
            if (current.left != null) {
                stack.push(current.left);
            }
        }
    }