Know Your Tree

You are given children, a matrix that describes a rooted binary tree. Let N = children.length; the nodes are numbered from 0 to N - 1. For every node i, children[i][0] is its left child and children[i][1] is its right child. A value of -1 means that the corresponding child does not exist.

Return a matrix of strings with one row for every node, ordered by increasing node ID. The row for node i must contain exactly four values: the node ID, its parent ID, its depth, and its type. Represent the numeric values as decimal strings.

The root has parent -1 and depth 0. Its type is ROOT. Every non-root node with at least one child has type INTERNAL, and every non-root node with no children has type LEAF. ROOT takes precedence when the tree contains only one node.

Implement describeTree(vector<vector<int>>& children).

Example 1:

Input: children = [[1, 2], [-1, 3], [-1, -1], [-1, -1]]

Output: [["0", "-1", "0", "ROOT"], ["1", "0", "1", "INTERNAL"], ["2", "0", "1", "LEAF"], ["3", "1", "2", "LEAF"]]

Explanation: Node 0 is the root. Node 1 has child 3, so it is internal. Nodes 2 and 3 have no children and are leaves.

Example 2:

Input: children = [[-1, -1], [0, 2], [-1, -1], [1, 4], [-1, -1]]

Output: [["0", "1", "2", "LEAF"], ["1", "3", "1", "INTERNAL"], ["2", "1", "2", "LEAF"], ["3", "-1", "0", "ROOT"], ["4", "3", "1", "LEAF"]]

Explanation: Node 3 is the only node that never appears as a child, so it is the root. The returned rows remain ordered by node ID, not by traversal order.

Now Your Turn!

Pick the correct output for the given input

Input: children = [[-1, -1]]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= children.length <= 1000
  • children[i].length = 2 for every 0 <= i < children.length
  • Each value in children is either -1 or a node ID in the range [0, children.length - 1].
  • A node is not its own child.
  • If both children of a node exist, their IDs are different.
  • Exactly one node never appears as a child; this node is the root.
  • Every other node appears exactly once among all child entries.
  • The child relationships form one connected, acyclic binary tree.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
vector<vector<string>> describeTree(vector<vector<int>>& children) {
// Your code goes here
return {};
}
};
Test Case

Input:

Children