Validate Binary Tree Nodes

You have n binary tree nodes numbered from 0 to n - 1, where node i has two children leftChild[i] and rightChild[i].

Return true if and only if all the given nodes form exactly one valid binary tree.

If node i has no left child, then leftChild[i] will equal -1; similarly, if node i has no right child, then rightChild[i] will equal -1.

Note that the nodes have no values, and only the node numbers are used in this problem.

Example 1
Inputn = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]
Outputtrue
The four nodes are connected as one valid binary tree.
Example 2
Inputn = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1]
Outputfalse
Node 3 has more than one parent, so the nodes do not form a valid binary tree.

Constraints

  • n == leftChild.length == rightChild.length
  • 1 <= n <= 10^4
  • -1 <= leftChild[i], rightChild[i] <= n - 1

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate