#K64742. Find Node Depth in a Binary Tree
Find Node Depth in a Binary Tree
Find Node Depth in a Binary Tree
You are given a binary tree and an integer target value. Your task is to determine the depth of the node that contains the target value. The depth of a node is defined as the number of edges from the root node to that node. Formally, for a node with depth \( d \), the root has depth \( 0 \) and any child node has depth \( d+1 \).
If the target value does not exist in the tree, output \(-1\).
The binary tree is provided in level order where the value null
indicates a missing node. The first line of input contains the level-order traversal of the tree (node values separated by spaces), and the second line contains the target integer.
Example:
Input: 3 9 20 null null 15 7 15</p>Output: 2
inputFormat
The input consists of two lines:
- The first line contains the level order traversal of the binary tree. Node values are separated by a space. Use
null
to denote a missing node. - The second line contains a single integer representing the target value whose depth is to be found.
Note that the tree could be empty; in such a case, the first token will be null
.
outputFormat
Output a single integer which is the depth of the node containing the target value. If the target value does not exist in the tree, output -1
.
3 9 20 null null 15 7
15
2