Search code examples
algorithm

How to construct a binary tree from Leetcode values list?


For the following problem:

enter image description here

The output/correct result is specified as:

 Output: [3,9,20,null,null,15,7]

I'm not sure what that output actually represents. I tried to scan it by level . E.g 3 is the root, then its children are 9 and 20 (which does not work). So then what is the actual tree?


Solution

  • It's how the binary tree is represented.

    Output is a list of nodes where for node i (starting from index 0), node 2*i+1 is its left child and node 2*i+2 is its right child. So if those nodes do not exist, the corresponding value in the list is represented as NULL.

    In this case, node 0 has a value of 3, and its left child is shown in node 1 (Output[1]) with value 9, while its right child is shown in node 2 (Output[2]) with value 20.

    However, node 2 (Output[2] with value 20) does not have any children so the values corresponding to its children (Output[3], Output[4]) are shown as Null.