Implement Binary Tree with Traversals
MediumP1Coding
Implement a binary tree that supports insertion and the four standard traversals.
Implement the BinaryTree class:
BinaryTree()creates an empty tree.insert(val)adds a node in the first free position when filling the tree level by level, left to right (so the tree is always complete). The first value becomes the root, the second its left child, the third its right child, and so on.inorder(),preorder()andpostorder()return the values as a list.levelOrder()returns a list of lists, one per level, from the root down.
An empty tree returns [] from every traversal. Duplicate values are allowed.
Example 1
- Input
- ["BinaryTree","insert","insert","insert","inorder","preorder","postorder","levelOrder"] [[],[1],[2],[3],[],[],[],[]]
- Output
- [null,null,null,null,[2,1,3],[1,2,3],[2,3,1],[[1],[2,3]]]
Constraints
- -10^9 <= val <= 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.