Write a method named completeToLevel
that adds nodes to a binary tree of integers so that the first n
levels are complete.
A level is complete if every possible node at that level is not null
.
Your method accepts as its parameters a TreeNode
that refers to the root of the tree, and an integer n
, and returns the tree's updated root.
We will use the convention that the overall root is at level 1
, it's children are at level 2
, and so on.
You should preserve any existing nodes in the tree.
Any new nodes added to the tree should have -1
as their data.
For example, suppose a variable called tree
refers to the root of the following tree:
(17 (83 (19 / (48))) (6 / (87 (75))))
The call of completeToLevel(tree, 3)
should return the root of the tree with the following updated state:
(17 (83 (19 / (48)) (-1)) (6 (-1) (87 (75))))
In this case, the request was to fill in nodes as necessary to ensure that the first 3 levels are complete.
There were two nodes missing at level 3.
Notice that level 4 of this tree is not complete because the call requested that nodes be filled in to level 3 only.
You may assume that the level passed will be at least 1
.
Assume that you are interacting with TreeNode
s as defined below:
public class TreeNode {
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode() { ... }
public TreeNode(int data) { ... }
public TreeNode(int data, TreeNode left, TreeNode right) { ... }
}