Binary Tree Representation (C++)
Learning Traversals DSA practice problem on Onlearn.
Difficulty: easy.
Topics: How is a binary tree represented in C++ using pointers, and how are nodes structured, created, and connected?, Data Structures, Binary Tree, Node, Pointer, Traversal, Recursion, Tree Construction, In-order Traversal, binary tree representation, general programming, node structure, tree properties, Binary Tree, Pointers & References, Node.
Problem Statement In C++, a binary tree is typically represented using a structure or class where each node contains data and pointers to the left and right children. Your task is to implement a program that constructs a binary tree from a given level order input array and then retrieves specific nodes based on their depth. Specifically, you need to perform an in order traversal of the constructed tree to find and print all nodes located at a specific depth $D$. Note: The root node is considered to be at depth 0. In the input array, a value of 1 indicates a NULL (empty) node. The tree should be constructed dynamically using pointers. Input Specification The first line contains a sequence of space separated integers representing the level order traversal of the binary tree. 1 indicates a NULL node. The second line contains a single integer $D$, representing the target depth. Output Specification Print the values of all nodes present at depth $D$, separated by spaces. The nodes should be printed in the order they are encountered during an in order traversal (which will correspond to left to right order for a specific depth). If no nodes exist at the specified depth, print nothing. Constraints 1 ≤ Number of nodes ≤ 10^5 10^9 ≤ Node values ≤ 10^9 (excluding 1 used for NULL) 0 ≤ D ≤ Height of the tree Sample Test Cases Sample Input 1 Sample Output 1 Explanation: The tree constructed is: 1 (Depth 0) / \ 2 3 (Depth 1) / \ 4 5 (Depth 2) The target depth is 2. The nodes at depth 2 are 4 and 5. Sample Input 2 Sample Output 2 Explanation: The tree constructed is: 10 / \ 20 30 / \ / \ 40 50 60 70 Nodes at depth 1 are 20 and 30. Sample Input 3 Sample Output 3 Explanation: The tree is a right skewed tree: 1 2 3. Node 1 is at depth 0. Node 2 is at depth 1. Node 3 is at depth 2. The output for depth 2 is 3. Difficulty Level Easy