Question

In: Computer Science

Write a binary search tree with 10 nodes in Java, each node will have 3 attributes...

Write a binary search tree with 10 nodes in Java, each node will have 3 attributes (data, x, y). The binary tree need to have function "add()" to add new node into the tree. After added all 10 nodes, it will be sorted and turn into a balanced binary search tree.

Solutions

Expert Solution

NOTE:If you have any doubts or confusion please feel free to ask in the comments but do not give negative rating to the question as it affects my answering rights......i will try my best to help you understand the question

Hope you know what a preorder traversal is and you can interpret a tree based on the preorder traversal...it will help you understand the working of the recursion to build a balanced binary tree.Also all the functions are recursion based make sure you understand them

The code works perfectly well...you can just copy paste the code to any online editor and see it work

import java.util.*; 
import java.io.*;

//x refers to left child and y refers to right child of a node
class Node //this class represents a single node in the tree
{ 
        int data; 
        Node x, y; 

        public Node(int data) 
        { 
                this.data = data; 
                x = y = null; 
        } 
} 

public class BinaryTree 
{ 
        Node root; 

        /* This function traverse the skewed binary tree and 
        stores its nodes pointers in vector nodes[] */
        void inorder(Node root, Vector<Node> nodes) 
        { 
                // Base case 
                if (root == null) 
                        return; 

                // Store nodes in Inorder (which is sorted 
                // order for BST) 
                inorder(root.x, nodes); 
                nodes.add(root); 
                inorder(root.y, nodes); 
        } 
    Node balancedTree(Vector<Node> nodes, int start, int end)  
    { 
        //the idea is to get the middle index and divide the vector based on this index
        
            // base case 
            if (start > end) 
                return null; 
      
            /* Get the middle element and make it root */
            int mid = (start + end) / 2; 
            Node node = nodes.get(mid); 
      
            /* Using index in Inorder traversal, construct 
               left and right subtress */
            node.x = balancedTree(nodes, start, mid - 1); 
            node.y = balancedTree(nodes, mid + 1, end); 
      
            return node; 
        } 
      
    // This functions converts an unbalanced BST to 
    // a balanced BST 
    Node buildTree(Node root)  
    { 
        //The first and the foremost requirement is that we need a sorted array of given binary tree
        //so the most simple approach is to do the inorder traversal of the tree and store the visited node in the same
        //order in a vector ,Hence we called the inorder func and stored the sorted nodes in a vector named nodes
        Vector<Node> nodes = new Vector<Node>(); 
        inorder(root, nodes); 
  
        // Constucts BST from nodes[] 
        int n = nodes.size(); 
        return balancedTree(nodes, 0, n - 1); //now recursively call the utilityfunction which is balancedTree here
    } 

    //the idea of adding a node is simple 
    //if the tree is empty make the data as root node
    //if the new node is less than the current node than move to the left child which is x here
    //if the new node is more than the curent node than move to the right child which is y here
        Node add(Node root,int n_data) 
        { 
            Node tmp=root;
            if(root == null){
                root=new Node(n_data);
                return root;
            }
            if (n_data < root.data) 
            root.x = add(root.x, n_data); 
        else if (n_data > root.data) 
            root.y = add(root.y, n_data); 
  
        return root; 
        } 

    //this function gives the preorder traversal of a tree
    //this is here to confirm if out program worked or not
        void preOrder(Node node) 
        { 
                if (node == null) 
                        return; 
                System.out.print(node.data + " "); 
                preOrder(node.x); 
                preOrder(node.y); 
        } 

        public static void main(String[] args) 
        { 
            Scanner sc=new Scanner(System.in);
                BinaryTree tree = new BinaryTree(); 
                System.out.println("Enter the nodes :"); 
            for(int i=0;i<10;i++){
             int tmp;
             tmp=sc.nextInt();
             tree.root= tree.add(tree.root,tmp);
            }
            System.out.println("Preorder traversal of BST is :"); 
            tree.preOrder(tree.root); 
            tree.root = tree.buildTree(tree.root); 
                System.out.println("\nPreorder traversal of balanced BST is :"); 
                tree.preOrder(tree.root); 
        } 
} 

Output:-->


Related Solutions

Write a binary search tree and include the functions to find the number of nodes and...
Write a binary search tree and include the functions to find the number of nodes and the height of the tree. Test your code in main. Print the post-order, in-order and pre-order traversal. in c++ please.
(IN C) Write the code to manage a Binary Tree. Each node in the binary tree...
(IN C) Write the code to manage a Binary Tree. Each node in the binary tree includes an integer value and string. The binary tree is sorted by the integer value. The functions include: • Insert into the binary tree. This function will take in as parameters: the root of the tree, the integer value, and the string. Note that this function requires you to create the node. • Find a node by integer value: This function takes in two...
In java, create a binary search tree (without using additional libraries) of stacks where each node...
In java, create a binary search tree (without using additional libraries) of stacks where each node contains a key and a stack. In this binary search tree, when adding a new element to the tree it is inserted based off of its key value; if that key value already exist then the element is pushed into the stack at that location, if the key value does not exist a node element is added to the tree to reflect that key,...
Write the code to manage a Binary Tree. Each node in the binary tree includes an integer value and string.
Programming CWrite the code to manage a Binary Tree. Each node in the binary tree includes an integer value and string. The binary tree is sorted by the integer value. The functions include:• Insert into the binary tree. This function will take in as parameters: the root of the tree, the integer value, and the string. Note that this function requires you to create the node.• Find a node by integer value: This function takes in two parameters: the root...
Question 3: Create a method for the Binary Search Tree (deleteNode) that deletes a specified node...
Question 3: Create a method for the Binary Search Tree (deleteNode) that deletes a specified node identified by its value, and rearranges the descendants of the deleted node to ensure the resulting Tree meets the requirements of a Binary Search Tree. a) Discuss and justify your approach to address each possible case. b) Is the new tree (with the deleted node removed) unique? Discuss your answer. Discuss method's Big-O notation. Add proper and consistent documentation to identify code sections or...
a tree is binary, if every node has at most two children nodes. prove that the...
a tree is binary, if every node has at most two children nodes. prove that the maximum of nodes in a binary tree of height h is 2^(h+1)-1
Create a binary search tree of stacks where each node contains a key and a stack.
IN C++   Create a binary search tree of stacks where each node contains a key and a stack. In this binary search tree, when adding a new element to the tree it is inserted based off of its key value; if that key value already exist then the element is pushed into the stack at that location, if the key value does not exist a node element is added to the tree to reflect that key, and a empty...
You are given a reference to the root node of a binary search tree, that implements...
You are given a reference to the root node of a binary search tree, that implements a dictionary data structure. Please print all the elements in depths 500 through 510, all in sorted order. A node in a binary search tree is at depth x, if it takes x hops to get from the root. So the root is at depth 0, the children of the root are at depth 1, and so on. The class TreeNode defines a single...
PYTHON CODING Using the structural node and methods discussed in Binary Search Tree below # Binary...
PYTHON CODING Using the structural node and methods discussed in Binary Search Tree below # Binary Tree Node structure class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None class BSTree(): def __init__(self, rootdata): self.root = Node(rootdata)    def insert(self, data, cur_node): if data < cur_node.data: if cur_node.left == None: cur_node.left = Node(data) else: self.insert(data, cur_node.left)    elif data > cur_node.data: if cur_node.right == None: cur_node.right = Node(data) else:...
1. Draw a binary search tree as a single root node holding a string as the...
1. Draw a binary search tree as a single root node holding a string as the data element. Each string inserted into a node in the tree will be for a character in a game. Then, draw a new tree each time you insert a new node into the tree holding a string Insert 4 nodes total, including the root. This means the new nodes will need to be inserted at the correct child to maintain the BST property.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT