I have the following solution to this problem. The idea is to compute the maximum width of a binary search tree. The width of a BST on a particular depth is defined as the distance from the leftmost non-null node to the rightmost non-null node at that depth. This implementation proceeds downwards from the root node in breadth-first manner keeping track of the width of the widest tree level until an empty level is encountered. (Note that the widest level isn’t necessarily the deepest one.
class TreeNode {
int val;
int num;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
public int widthOfBinaryTree(TreeNode root) {
TreeNode[] levelHi = new TreeNode[3_000];
TreeNode[] levelLo = new TreeNode[3_000];
levelHi[0] = root;
root.num = 0;
int maximumWidth = 1;
int levelLength = 1;
while (true) {
int numberOfChildrenInLoLevel =
getNextDeepestLevel(levelHi, levelLo, levelLength);
if (numberOfChildrenInLoLevel == 0) {
return maximumWidth;
}
int tentativeWidth = levelLo[numberOfChildrenInLoLevel - 1].num -
levelLo[0].num + 1;
maximumWidth = Math.max(maximumWidth, tentativeWidth);
TreeNode[] levelTemp = levelLo;
levelLo = levelHi;
levelHi = levelTemp;
levelLength = numberOfChildrenInLoLevel;
}
}
int getNextDeepestLevel(TreeNode[] levelHi,
TreeNode[] levelLo,
int levelHiLength) {
int levelLoLength = 0;
for (int i = 0; i < levelHiLength; i++) {
TreeNode currentTreeNode = levelHi[i];
TreeNode leftChild = currentTreeNode.left;
TreeNode rightChild = currentTreeNode.right;
if (leftChild != null) {
leftChild.num = currentTreeNode.num * 2;
levelLo[levelLoLength++] = leftChild;
}
if (rightChild != null) {
rightChild.num = currentTreeNode.num * 2 + 1;
levelLo[levelLoLength++] = rightChild;
}
}
return levelLoLength;
}
}
Critique request
I would like to hear comments about efficiency and space consumption.
TreeNode
two arrays (in case of sparse tree with lot of a null nodes maybe could be a difference) ? \$\endgroup\$