Algorithms and Data Structures

  • Profound Academy

    • Status
      • 1
        Implementation
      • 2
        Bitwise operations
      • 3
        Prefix Sums
      • 4
        Sliding window / Two pointers
      • 5
        Modular Arithmetic
      • 6
        Number Theory
      • 7
        Binary Search
      • 8
        Basic Sorting
      • 9
        Greedy Algorithms
      • 10
        Basic Dynamic Programming
      • 11
        Recursion
      • 12
        Linked LIst
      • 13
        Queue & Stack
      • 14
        Binary tree + BST
      • 15
        Divide & Conquer + Advanced Sorting
      • 16
        Heap
      • 17
        Hashing
      • 18
        Graph Representation
      • 19
        BFS

  • Pre-order traversal of a binary tree

    Pre-order traversal of a tree is a recursive procedure, where you first visit a node, then visit its left subtree, then visit its right subtree:
    1. Visit the current node
    1. Visit the left subtree (node.left)
    1. Visit the right subtree (node.right)
    Given a binary tree, you are asked to perform a pre-order traversal on it.

    Input

    The input contains space-separated integers representing the values in the nodes of the binary tree. The order of the values is given as described in the previous statement (by traversing from the left to the right subtree every time). A value of 0 means that the node does not exist. It’s guaranteed that the input binary tree is valid.

    Output

    The program should print the values in the nodes of a binary tree when performing a pre-order traversal. All the values should be separated by a space.

    Examples

    Input
    Output
    1 2 3 4 5 8 9 0 0 0 0 0 0 6 7 0 0 0 0
    1 2 4 8 9 5 3 6 7
    1 2 3 4 5 8 0 0 0 0 0 6 7 0 0 0 0
    1 2 4 8 5 3 6 7
    1 2 3 4 5 0 0 0 0 6 7 0 0 8 9 0 0 0 0
    1 2 4 5 3 6 7 8 9
    1 2 3 4 5 0 0 7 8 0 0 0 0 0 6 0 0
    1 2 4 5 7 8 3 6

    Explanation

    1. Example 1:
      1. notion image
    1. Example 2:
      1. notion image
    1. Example 3:
      1. notion image
    1. Example 4:
      1. notion image
     

    Constraints

    Time limit: 1 seconds

    Memory limit: 512 MB

    Output limit: 1 MB

    To check your solution you need to sign in
    Sign in to continue