Skip to content
Onsite

Implement N-ary Tree

MediumP3Coding

Implement an N-ary tree: every node can have any number of children, kept in the order they were added. All values in the tree are unique.

Implement the NaryTree class:

  • NaryTree(rootVal) creates a tree with a single root node.
  • addChild(parentVal, val) adds a new node with value val as the last child of the node whose value is parentVal and returns true. If parentVal is not in the tree, or val is already in the tree, change nothing and return false.
  • find(val) returns true if a node with that value exists.
  • preorder() returns the values visiting a node before its children, children left to right.
  • levelOrder() returns a list of lists, one per depth, left to right.
  • height() returns the number of nodes on the longest root-to-leaf path (a lone root has height 1).

Example 1

Input
["NaryTree","addChild","addChild","addChild","preorder","levelOrder","height"] [[1],[1,2],[1,3],[2,4],[],[],[]]
Output
[null,true,true,true,[1,2,4,3],[[1],[2,3],[4]],3]
Why
Root 1 has children 2, 3; node 2 has child 4.

Constraints

  • -10^9 <= values <= 10^9
  • At most 1000 calls in total.

Hints

Run checks the 2 visible tests, Submit all 7.