Tree: Preorder Traversal

Sort by

recency

|

16 Discussions

|

  • + 0 comments

    Here is Hackerrank Tree preorder traversal problem solution in Python, Java, c++ c and javascript

  • + 0 comments

    JAVA

    public static void preOrder(Node root) {
    
        if (root == null) {
            return;
        }
        // visit the root
        System.out.print(root.data + " ");
        // traverse the left
        preOrder(root.left);
        // traverse the right
        preOrder(root.right);
    }
    
  • + 0 comments
    # Recursive version using Function Stack:
    def preOrder(root):
        print(root.info, end=' ')
        if root.left:
            preOrder(root.left)
        if root.right:
            preOrder(root.right)
    
  • + 1 comment
    def preOrder(root):
        stack = [root]
        while stack:
            curr_node = stack.pop()
            print(curr_node.info, end=' ')
            if curr_node.right:
                stack.append(curr_node.right)
            if curr_node.left:
                stack.append(curr_node.left)
    
  • + 0 comments

    By "binary tree" they obviously mean "binary search tree"

    Otherwise one can construct more than one binary tree from the provided linear input...

    I wish them to get such an ambiguous problem on their interview.