Tree: Preorder Traversal

Sort by

recency

|

448 Discussions

|

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

    Very Simple Javascript Recursive Solution

    const resp = []

    function helperFunc(root) { if(!root) return; resp.push(root.data) helperFunc(root.left); helperFunc(root.right); }

    function preOrder(root) { helperFunc(root); console.log(resp.join(' ')); }

  • + 0 comments

    Very Simple Javascript Recursive Solution

    const resp = []

    function helperFunc(root) { if(!root) return; resp.push(root.data) helperFunc(root.left); helperFunc(root.right); }

    function preOrder(root) { helperFunc(root); console.log(resp.join(' ')); }

  • + 0 comments

    class Node: def init(self, info): self.info = info
    self.left = None
    self.right = None self.level = None

    def __str__(self):
        return str(self.info) 
    

    class BinarySearchTree: def init(self): self.root = None

    def create(self, val):  
        if self.root == None:
            self.root = Node(val)
        else:
            current = self.root
    
            while True:
                if val < current.info:
                    if current.left:
                        current = current.left
                    else:
                        current.left = Node(val)
                        break
                elif val > current.info:
                    if current.right:
                        current = current.right
                    else:
                        current.right = Node(val)
                        break
                else:
                    break
    

    """ Node is defined as self.left (the left child of the node) self.right (the right child of the node) self.info (the value of the node) """ def preOrder(root): if(root==None): return 0 print(root.info, end=" ") preOrder(root.left) preOrder(root.right)

    tree = BinarySearchTree() t = int(input())

    arr = list(map(int, input().split()))

    for i in range(t): tree.create(arr[i])

    preOrder(tree.root)

  • + 0 comments

    JavaScript solution using recursion

    function preOrder(root) {
        let res = '';
        function abc(root){
          if(root){
            res = res + root.data + '  ';
            abc(root.left);
            abc(root.right)  
           }
        }
        abc(root);
        console.log(res)
    }