Skip to main content

Add all smallest values to every node in a given BST

Add all smallest keys in BST

Here given code implementation process.

// C Program 
// Add all smallest values to every node in a given BST
#include<stdio.h>
#include<stdlib.h>
//structure of Binary Search Tree node
struct Node
{
  int data;
  struct Node *left,*right; 
};

//Adding a new node in binary search tree
void add( struct Node **root, int data)
{
  //Create a dynamic node of binary search tree 
  struct Node *new_node = (struct Node *)malloc(sizeof(struct Node ));

  if(new_node!=NULL)
  {
    //Set data and pointer values
    new_node->data = data;
    new_node->left = NULL; //Initially node left-pointer is NULL
    new_node->right = NULL;//Initially node right-pointer is NULL

    if(*root == NULL)
    {
      //When adds a first node in binary tree
      *root = new_node;
    }
    else
    {
      struct Node *find = *root;
      //iterate binary tree and add new node to proper position
      while(find != NULL)
      {
        if(find -> data > data)
        { 
          if(find->left==NULL)
          {
            find->left = new_node;
            break;
          }
          else
          { //visit left sub-tree
            find = find->left;
          }
        }
        else
        {
          if(find->right == NULL)
          {
            find->right = new_node;
            break;
          }
          else
          {
            //visit right sub-tree
            find = find->right;
          }
        }
      }
    }
  }else
  {
    printf("Memory Overflow\n");
    exit(0); //Terminate program execution
  }

}


void convert(struct Node*root,int *prev)
{
  if(root != NULL)
  {
    
    convert(root->left,prev);
      
      *prev+=root->data;
    
      root->data= *prev;
     
    convert(root->right,prev);
  
  }
 
}
void inorder(struct Node*root)
{
  if(root!=NULL)
  {
    
    inorder(root->left);
    printf("%3d ",root->data );
    inorder(root->right);
  }
}
int main(){
    
  struct Node*root = NULL;

  //Add nodes in binary search tree
  /*
             5
           /    \
          3      9
         / \     / \
        2   4   8   11
       /       /      \
      1       7        12


  */                


    add(&root,5); 
    add(&root,3); 
    add(&root,9); 
    add(&root,2); 
    add(&root,4); 
    add(&root,8); 
    add(&root,11); 
    add(&root,1); 
    add(&root,7); 
    add(&root,12); 
  
  printf("Before\n");
  inorder(root);
  int prev=0;
  convert(root,&prev);

  printf("\nAfter\n");
  inorder(root);
  return 0;
}

Output

Before
  1   2   3   4   5   7   8   9  11  12 
After
  1   3   6  10  15  22  30  39  50  62
/*
 C++ Program
 Add all smallest values to every node in a given BST
*/

#include <iostream>

using namespace std;
class Node {
  public:
    int data;
  Node *left;
  Node *right;
  Node(int value) {
    this->data = value;
    this->left = NULL;
    this->right = NULL;
  }
};
class BinarySearchTree {
  public:
    Node *root;
  int result;
  BinarySearchTree() {
    this->root = NULL;
    this->result = 0;
  }
  void add(int value) {
    Node *new_node = new Node(value);
    if (new_node != NULL) {
      if (this->root == NULL) {
        this->root = new_node;
      } else {
        Node *find = this->root;
        while (find != NULL) {
          if (find->data >= value) {
            if (find->left == NULL) {
              find->left = new_node;
              break;;
            } else {
              find = find->left;
            }
          } else {
            if (find->right == NULL) {
              find->right = new_node;
              break;;
            } else {
              find = find->right;
            }
          }
        }
      }
    } else {
      cout << "\nMemory Overflow\n";
    }
  }
  void inorder(Node *head) {
    if (head != NULL) {
      this->inorder(head->left);
      cout << head->data << "  ";
      this->inorder(head->right);
    }
  }
  void update_record(Node *head) {
    if (head != NULL) {
      this->update_record(head->left);
      head->data += this->result;
      this->result = head->data;
      this->update_record(head->right);
    }
  }
  void convert() {
    if (this->root != NULL) {
      this->result = 0;
      this->update_record(this->root);
    } else {
      cout << "\nEmpty BST\n";
    }
  }
};

int main() {
  BinarySearchTree obj;
  /*
             5
           /    \
          3      9
         / \     / \
        2   4   8   11
       /       /      \
      1       7        12


  */                

  obj.add(5);
  obj.add(3);
  obj.add(9);
  obj.add(2);
  obj.add(4);
  obj.add(8);
  obj.add(11);
  obj.add(1);
  obj.add(7);
  obj.add(12);
  cout << "Before \n";
  obj.inorder(obj.root);
  obj.convert();
  cout << "\nAfter \n";
  obj.inorder(obj.root);

  return 0;
}

Output

Before
  1   2   3   4   5   7   8   9  11  12 
After
  1   3   6  10  15  22  30  39  50  62
//Java program
//Add all smallest values to every node in a given BST

//BST node
class Node {

  public int data;
  public Node left;
  public Node right;

  public Node(int value) {
    data = value;
    left = null;
    right = null;
  }
}
public class BinarySearchTree {


  public Node root;

  public int result;

  public BinarySearchTree()
  {
    root = null;
    result = 0;
  }
  //insert a node in BST
  public void add(int value)
  {
    //Create a dynamic node of binary search tree 
    Node new_node = new Node(value);

    if(new_node != null)
    {
      if(root == null)
      {
        //When adds a first node in binary tree
        root = new_node;
      }
      else
      {
        Node find = root;

        //add new node to proper position
        while(find != null)
        {
          if(find.data >= value)
          { 
            if(find.left==null)
            {
              find.left = new_node;
              break;
            }
            else
            { 
              //visit left sub-tree
              find = find.left;
            }
          }
          else
          {
            if(find.right == null)
            {
              find.right = new_node;
              break;
            }
            else
            {
              //visit right sub-tree
              find = find.right;
            }
          }
        }
      }
    }
    else
    {
      System.out.print("\nMemory Overflow\n");
    }
  }

  public void inorder(Node head) {
    if (head != null) {

      inorder(head.left);
      System.out.print(head.data + "  ");
      inorder(head.right);
    }
  }
  public void update_record(Node head)
  {
    if(head != null)
    {
      update_record(head.left);
      
      head.data +=  this.result;

      this.result=head.data;
      
      update_record(head.right);
     
    }

  }
  public void convert()
  {
    if(root!=null)
    {
      this.result = 0;

      update_record(root);
    }
    else
    {
      System.out.print("\nEmpty BST\n");
    }
  }

  public static void main(String[] args) {

    BinarySearchTree obj = new BinarySearchTree();
    //Add nodes in binary search tree
    /*
               5
             /    \
            3      9
           / \     / \
          2   4   8   11
         /       /      \
        1       7        12


    */                


    obj.add(5); 
    obj.add(3); 
    obj.add(9); 
    obj.add(2); 
    obj.add(4); 
    obj.add(8); 
    obj.add(11); 
    obj.add(1); 
    obj.add(7); 
    obj.add(12); 
    System.out.print("Before \n");
    obj.inorder(obj.root);
    obj.convert();
    System.out.print("\nAfter \n");
    obj.inorder(obj.root);
  }
}

Output

Before
  1   2   3   4   5   7   8   9  11  12 
After
  1   3   6  10  15  22  30  39  50  62
//C# program
//Add all smallest values to every node in a given BST
using System;
//BST node
public class Node {

	public int data;
	public Node left;
	public Node right;

	public Node(int value) {
		data = value;
		left = null;
		right = null;
	}
}
public class BinarySearchTree {


	public Node root;

	public int result;

	public BinarySearchTree()
	{
		root = null;
		result = 0;
	}
	//insert a node in BST
	public void add(int value)
	{
		//Create a dynamic node of binary search tree 
		Node new_node = new Node(value);

		if(new_node != null)
		{
			if(root == null)
			{
				//When adds a first node in binary tree
				root = new_node;
			}
			else
			{
				Node find = root;

				//add new node to proper position
				while(find != null)
				{
					if(find.data >= value)
					{ 
						if(find.left==null)
						{
							find.left = new_node;
							break;
						}
						else
						{ 
							//visit left sub-tree
							find = find.left;
						}
					}
					else
					{
						if(find.right == null)
						{
							find.right = new_node;
							break;
						}
						else
						{
							//visit right sub-tree
							find = find.right;
						}
					}
				}
			}
		}
		else
		{
			Console.Write("\nMemory Overflow\n");
		}
	}

	public void inorder(Node head) {
		if (head != null) {

			inorder(head.left);
			Console.Write(head.data + "  ");
			inorder(head.right);
		}
	}
	public void update_record(Node head)
	{
		if(head != null)
		{
			update_record(head.left);

			head.data +=  this.result;

			this.result=head.data;

			update_record(head.right);

		}

	}
	public void convert()
	{
		if(root!=null)
		{
			this.result = 0;

			update_record(root);
		}
		else
		{
			Console.Write("\nEmpty BST\n");
		}
	}

	public static void Main(String[] args) {

		BinarySearchTree obj = new BinarySearchTree();
		//Add nodes in binary search tree
		/*
               5
             /    \
            3      9
           / \     / \
          2   4   8   11
         /       /      \
        1       7        12


    */                


		obj.add(5); 
		obj.add(3); 
		obj.add(9); 
		obj.add(2); 
		obj.add(4); 
		obj.add(8); 
		obj.add(11); 
		obj.add(1); 
		obj.add(7); 
		obj.add(12); 
		Console.Write("Before \n");
		obj.inorder(obj.root);
		obj.convert();
		Console.Write("\nAfter \n");
		obj.inorder(obj.root);
	}
}

Output

Before
  1   2   3   4   5   7   8   9  11  12 
After
  1   3   6  10  15  22  30  39  50  62
# Python 3 Program
# Add all smallest values to every node in a given BST

class Node :
  def __init__(self, value) :
    self.data = value
    self.left = None
    self.right = None
  

class BinarySearchTree :

  def __init__(self) :
    self.root = None
    self.result = 0
  
  def add(self, value) :
    new_node = Node(value)
    if (new_node != None) :
      if (self.root == None) :
        self.root = new_node
      else :
        find = self.root
        while (find != None) :
          if (find.data >= value) :
            if (find.left == None) :
              find.left = new_node
              break
            else :
              find = find.left
            
          else :
            if (find.right == None) :
              find.right = new_node
              break
            else :
              find = find.right
            
          
        
      
    else :
      print("\nMemory Overflow\n")
    
  
  def inorder(self, head) :
    if (head != None) :
      self.inorder(head.left)
      print(head.data ,end="  ")
      self.inorder(head.right)
    
  
  def update_record(self, head) :
    if (head != None) :
      self.update_record(head.left)
      head.data += self.result
      self.result = head.data
      self.update_record(head.right)
    
  
  def convert(self) :
    if (self.root != None) :
      self.result = 0
      self.update_record(self.root)
    else :
      print("\nEmpty BST\n")
    
  
def main() :
  obj = BinarySearchTree()
  #
  #             5
  #           /    \
  #          3      9
  #         / \     / \
  #        2   4   8   11
  #       /       /      \
  #      1       7        12
  #  
  obj.add(5)
  obj.add(3)
  obj.add(9)
  obj.add(2)
  obj.add(4)
  obj.add(8)
  obj.add(11)
  obj.add(1)
  obj.add(7)
  obj.add(12)
  print("Before ")
  obj.inorder(obj.root)
  obj.convert()
  print("\nAfter ")
  obj.inorder(obj.root)
  

if __name__ == "__main__":
  main()

Output

Before
  1   2   3   4   5   7   8   9  11  12 
After
  1   3   6  10  15  22  30  39  50  62
# Ruby Program
# Add all smallest values to every node in a given BST

class Node 
	attr_reader :data, :left, :right
	attr_accessor :data, :left, :right
	def initialize(value) 
		@data = value
		@left = nil
		@right = nil
	end
end

class BinarySearchTree 
	attr_reader :root, :result
	attr_accessor :root, :result
	def initialize() 
		@root = nil
		@result = 0
	end
	def add(value) 
		new_node = Node.new(value)
		if (new_node != nil) 
			if (@root == nil) 
				@root = new_node
			else 
				find = @root
				while (find != nil) 
					if (find.data >= value) 
						if (find.left == nil) 
							find.left = new_node
							break
						else 
							find = find.left
						end
					else 
						if (find.right == nil) 
							find.right = new_node
							break
						else 
							find = find.right
						end
					end
				end
			end
		else 
			print("\nMemory Overflow\n")
		end
	end
	def inorder(head) 
		if (head != nil) 
			self.inorder(head.left)
			print(head.data ,"  ")
			self.inorder(head.right)
		end
	end
	def update_record(head) 
		if (head != nil) 
			self.update_record(head.left)
			head.data += self.result
			self.result = head.data
			self.update_record(head.right)
		end
	end
	def convert() 
		if (@root != nil) 
			self.result = 0
			self.update_record(@root)
		else 
			print("\nEmpty BST\n")
		end
	end
end
def main() 
	obj = BinarySearchTree.new()
	#
	#             5
	#           /    \
	#          3      9
	#         / \     / \
	#        2   4   8   11
	#       /       /      \
	#      1       7        12
	#  
	obj.add(5)
	obj.add(3)
	obj.add(9)
	obj.add(2)
	obj.add(4)
	obj.add(8)
	obj.add(11)
	obj.add(1)
	obj.add(7)
	obj.add(12)
	print("Before \n")
	obj.inorder(obj.root)
	obj.convert()
	print("\nAfter \n")
	obj.inorder(obj.root)
end


main()

Output

Before
  1   2   3   4   5   7   8   9  11  12 
After
  1   3   6  10  15  22  30  39  50  62
<?php
/*
 Php Program
 Add all smallest values to every node in a given BST
*/

class Node {
  public $data;
  public $left;
  public $right;

  function __construct($value) {
    $this->data = $value;
    $this->left = null;
    $this->right = null;
  }
}
class BinarySearchTree {
  public $root;
  public $result;

  function __construct() {
    $this->root = null;
    $this->result = 0;
  }
  public  function add($value) {
    $new_node = new Node($value);
    if ($new_node != null) {
      if ($this->root == null) {
        $this->root = $new_node;
      } else {
        $find = $this->root;
        while ($find != null) {
          if ($find->data >= $value) {
            if ($find->left == null) {
              $find->left = $new_node;
              break;;
            } else {
              $find = $find->left;
            }
          } else {
            if ($find->right == null) {
              $find->right = $new_node;
              break;;
            } else {
              $find = $find->right;
            }
          }
        }
      }
    } else {
      echo("\nMemory Overflow\n");
    }
  }
  public  function inorder($head) {
    if ($head != null) {
      $this->inorder($head->left);
      echo($head->data ."  ");
      $this->inorder($head->right);
    }
  }
  public  function update_record($head) {
    if ($head != null) {
      $this->update_record($head->left);
      $head->data += $this->result;
      $this->result = $head->data;
      $this->update_record($head->right);
    }
  }
  public  function convert() {
    if ($this->root != null) {
      $this->result = 0;
      $this->update_record($this->root);
    } else {
      echo("\nEmpty BST\n");
    }
  }
}
function main() {
  $obj = new BinarySearchTree();
  /*
             5
           /    \
          3      9
         / \     / \
        2   4   8   11
       /       /      \
      1       7        12


  */                

  $obj->add(5);
  $obj->add(3);
  $obj->add(9);
  $obj->add(2);
  $obj->add(4);
  $obj->add(8);
  $obj->add(11);
  $obj->add(1);
  $obj->add(7);
  $obj->add(12);
  echo("Before \n");
  $obj->inorder($obj->root);
  $obj->convert();
  echo("\nAfter \n");
  $obj->inorder($obj->root);
}
main();

Output

Before
  1   2   3   4   5   7   8   9  11  12 
After
  1   3   6  10  15  22  30  39  50  62
/*
 Node Js Program
 Add all smallest values to every node in a given BST
*/

class Node {

	constructor(value) {
		this.data = value;
		this.left = null;
		this.right = null;
	}
}
class BinarySearchTree {
	constructor() {
		this.root = null;
		this.result = 0;
	}
	add(value) {
		var new_node = new Node(value);
		if (new_node != null) {
			if (this.root == null) {
				this.root = new_node;
			} else {
				var find = this.root;
				while (find != null) {
					if (find.data >= value) {
						if (find.left == null) {
							find.left = new_node;
							break;;
						} else {
							find = find.left;
						}
					} else {
						if (find.right == null) {
							find.right = new_node;
							break;;
						} else {
							find = find.right;
						}
					}
				}
			}
		} else {
			process.stdout.write("\nMemory Overflow\n");
		}
	}
	inorder(head) {
		if (head != null) {
			this.inorder(head.left);
			process.stdout.write(head.data + "  ");
			this.inorder(head.right);
		}
	}
	update_record(head) {
		if (head != null) {
			this.update_record(head.left);
			head.data += this.result;
			this.result = head.data;
			this.update_record(head.right);
		}
	}
	convert() {
		if (this.root != null) {
			this.result = 0;
			this.update_record(this.root);
		} else {
			process.stdout.write("\nEmpty BST\n");
		}
	}
}

function main() {
	var obj = new BinarySearchTree();
	/*
             5
           /    \
          3      9
         / \     / \
        2   4   8   11
       /       /      \
      1       7        12


    */                

	obj.add(5);
	obj.add(3);
	obj.add(9);
	obj.add(2);
	obj.add(4);
	obj.add(8);
	obj.add(11);
	obj.add(1);
	obj.add(7);
	obj.add(12);
	process.stdout.write("Before \n");
	obj.inorder(obj.root);
	obj.convert();
	process.stdout.write("\nAfter \n");
	obj.inorder(obj.root);
}


main();

Output

Before
  1   2   3   4   5   7   8   9  11  12 
After
  1   3   6  10  15  22  30  39  50  62
/*
  Swift 4 Program
  Add all smallest values to every node in a given BST
*/

class Node {
  var data: Int;
  var left: Node? ;
  var right: Node? ;
  init(_ value: Int) {
    self.data = value;
    self.left = nil;
    self.right = nil;
  }
}
class BinarySearchTree {
  var root: Node? ;
  var result: Int;
  init() {
    self.root = nil;
    self.result = 0;
  }
  func add(_ value: Int) {
    let new_node: Node? = Node(value);
    if (new_node != nil) {
      if (self.root == nil) {
        self.root = new_node;
      } else {
        var find: Node? = self.root;
        while (find != nil) {
          if (find!.data >= value) {
            if (find!.left == nil) {
              find!.left = new_node;
              break;
            } else {
              find = find!.left;
            }
          } else {
            if (find!.right == nil) {
              find!.right = new_node;
              break;
            } else {
              find = find!.right;
            }
          }
        }
      }
    } else {
      print("\nMemory Overflow\n");
    }
  }
  func inorder(_ head: Node? ) {
    if (head != nil) {
      self.inorder(head!.left);
      print(head!.data ,terminator : "  ");
      self.inorder(head!.right);
    }
  }
  func update_record(_ head: Node? ) {
    if (head != nil) {
      self.update_record(head!.left);
      head!.data += self.result;
      self.result = head!.data;
      self.update_record(head!.right);
    }
  }
  func convert() {
    if (self.root != nil) {
      self.result = 0;
      self.update_record(self.root);
    } else {
      print("\nEmpty BST\n");
    }
  }
}
func main() {
  let obj: BinarySearchTree = BinarySearchTree();
  /*
           5
         /    \
        3      9
       / \     / \
      2   4   8   11
     /       /      \
    1       7        12


  */                

  obj.add(5);
  obj.add(3);
  obj.add(9);
  obj.add(2);
  obj.add(4);
  obj.add(8);
  obj.add(11);
  obj.add(1);
  obj.add(7);
  obj.add(12);
  print("Before ");
  obj.inorder(obj.root);
  obj.convert();
  print("\nAfter ");
  obj.inorder(obj.root);
}
main();

Output

Before
  1   2   3   4   5   7   8   9  11  12 
After
  1   3   6  10  15  22  30  39  50  62




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment