Tree: Preorder Traversal

Sort by

recency

|

72 Discussions

|

  • + 0 comments

    The tricky part is how to convert input to the tree, other than the traversal...

  • + 0 comments

    This is one possible solution in python

    def preOrder(root):
        if root:
            print(root, end=' ')
            preOrder(root.left)
            preOrder(root.right)
    
  • + 0 comments

    C++ O(n)

    an elegant way to write it is by using recursion:

    void preOrder(Node *root) {
        if(root == NULL) return;
    
        std::cout << root->data << " ";
    
        preOrder(root->left);
        preOrder(root->right);
    }
    
  • + 0 comments

    This is a terribly written problem.

  • + 0 comments

    Java

    • visit the nodes in a order. left then right.
    • Recursive call on left sub tree.
    • Recursive call on right sub tree.
    public static void preOrder(Node root) {
            if(root != null){
                System.out.print(root.data+" ");
                preOrder(root.left);
                preOrder(root.right);
            }
        }