Create a binary tree [Huawei OD machine test 2023 Q1 test question A]

【Create a binary tree】

Please follow the following description to construct a binary tree and return the root node of the tree:

1. First create a root node with a value of -1, and the root node is at level 0;

2. Then add nodes in sequence according to operations: operations[i] = [height, index] means to add a child node whose value is i to the index node node of the height layer:

If node has no "left child node". Then add the left child node;
if the node has a "left child node" but no "right child node", then add the right child node:
otherwise, do nothing.

Both height and index start counting from 0; index refers to the creation sequence of the layer.

Example 1 The input and output examples are only for debugging, and the background judgment data generally does not include examples

enter

operations=[[0, 0], [0, 0], [1, 1], [1, 0], [0, 0]]
output

[-1, 0, 1, 3, null, 2]
Example 2 The input and output examples are only for debugging, and the background judgment data generally does not include examples

enter

operations=[[0, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1], [2, 0], [3, 1] , [2, 0]]
output

[-1, 0, null, 1, 2, 6, 8, 3, 4, null, null, null, null, null, null, 7]

Java

import java.util.*

Guess you like

Origin blog.csdn.net/weixin_54707168/article/details/129252036