Tree: Preorder Traversal

Sort by

recency

|

452 Discussions

|

  • + 0 comments

    In some languages like Kotlin it gives only a main fucntion which doesn't have a Node class. And there's no explanation how the single array, that the input is giving, is sorted... I spent hours trying to figure out what the tree from the input should look like and I was trying to write a function to create the tree with Node class... So then I switched to Java and saw that the node object is given...

  • + 0 comments
    
    

    void solve(Node* root) { if(root == NULL) { return; } cout<data<<" "; solve(root->left); solve(root->right); }

    
    

    solve(root);

    
    
  • + 0 comments

    Why it was showing main method in this?

  • + 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);
            }
        }
    }
    
  • + 0 comments

    My Java solution with linear time complexity and constant space complexity:

    public static void preOrder(Node root) {
            if(root == null) return; //no val to be printed
            
            //print val
            System.out.print(root.data + " ");
            
            //recursively traverse thru left nodes first, the through right nodes
            preOrder(root.left);
            preOrder(root.right);
        }