Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- D D
- / /
- A S --> A S
- / /
- N N Z
- (size = 4) (size = 5)
- 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)
- }
- 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);
- }
- }
- 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;
- }
- }
- 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;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement