I'm still not sure what your use case for storing the size of each subtree is, but it's easy to keep it updated during each insert without resorting to recursion. For the sake of simplicity, let's assume you start with the following definitions:
public static class BSTNode
{
public BSTNode leftTree = null;
public BSTNode rightTree = null;
public int subtreeSize = 1;
public int value;
public BSTNode(int valToAdd){
value = valToAdd;
}
}
public static class BST
{
public BSTNode root;
//public void insert(int valToAdd)
}
In the implementation of insert
, we'd start at the root and traverse the tree to find the appropriate place to add the new value. We can update each subtree's size as we go. A simple implementation might look like the following:
public void insert(int valToAdd)
{
if(root == null){
root = new BSTNode(valToAdd);
return;
}
BSTNode parent = root;
BSTNode current = root;
while(current != null){
parent = current;
++current.subtreeSize;
if(valToAdd <= current.value){
current = current.leftTree;
}
else{
current = current.rightTree;
}
}
if(valToAdd <= parent.value){
parent.leftTree = new BSTNode(valToAdd);
}
else{
parent.rightTree = new BSTNode(valToAdd);
}
}
There are cases where you want to update starting from the bottom, such as tracking subtree height (which may be used in rebalancing). Assume the BSTNode
definition is now:
public static class BSTNode
{
public BSTNode leftTree = null;
public BSTNode rightTree = null;
public int height = 0;
public int value;
public BSTNode(int valToAdd){
value = valToAdd;
}
}
In insert
, use a Stack
(or anything that can provide LIFO semantics) to store the ancestors of the newly inserted node. Modifying our previous simple example:
public void insert(int valToAdd)
{
if(root == null){
root = new BSTNode(valToAdd);
return;
}
java.util.Stack<BSTNode> stack = new java.util.Stack<BSTNode>();
BSTNode parent = root;
BSTNode current = root;
while(current != null){
parent = current;
stack.push(current);
if(valToAdd <= current.value){
current = current.leftTree;
}
else{
current = current.rightTree;
}
}
if(valToAdd <= parent.value){
parent.leftTree = new BSTNode(valToAdd);
}
else{
parent.rightTree = new BSTNode(valToAdd);
}
int height = 1;
while(!stack.isEmpty()){
current = stack.pop();
current.height = Math.max(height, current.height);
++height;
}
}