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 valuevalas the last child of the node whose value isparentValand returnstrue. IfparentValis not in the tree, orvalis already in the tree, change nothing and returnfalse.find(val)returnstrueif 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
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 2 visible tests, Submit all 7. ⌘Enter runs, ⌘⇧Enter submits.