Question

In Java Language

Please use: (do not change this part)

public int kSmallest(Node root, int k){

Only need this method done worry about creating a main method assume it is already done.(6) Given the root of a valid BST, return the kth smallest number without using more than 0(1) space. You can assume the Node

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The function that returns the integer required will be as following:

The recursive and using stack method uses extra space. But with no extra space we can think of one thing storing the Inorder predecessor which will help us loop back incase of leaf nodes. This procedure is analogous to having two pointers in c or c++. This is a modification known as Morrison In Order Traversal where we store link to inorder successor of the current node.

Procedure following below are :

1) Start traversing tree in order till the count becomes k

2) return the node's key on which the count becomes k.

Key: In order traversal , Space Complexity O(1)

First Left , Then Root, Then Right.

/******************************************************************************

Online Java Compiler.
Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.

*******************************************************************************/

public int kSmallest(Node root,int k){

int count = 0; // to count the minimum digits.

Node temp = root; // this will give us a temporary pointer to go through in order traversal of the tree

Node prev;

if (temp == null)

System.out.println("Root Empty!");

else{

while(temp! = null){

if (temp.left == null){// if the left node of temp is null that means it has 0 left child and next smallest is root turn so count will be

// incremented by 1 as we have reached the most minimum value from the BST

count++;

if ( count == k)
return temp.key ; // return the value of temp if the count equals k i.e. kth smallest node.


temp = temp.right; // we move to the right subtree after recording the root and incrementing count for it.
}
else {
// if the left child is present then we have to store the inorder successor which Means the inorder node which would occur after traversing more down
// the tree.
  
prev = temp.left ;
while (prev.right != null && prev.right != temp) // here we make links to inorder successor and use links to count our kth smallest.
prev = prev.right; // here prev will reach till the node where the backlink needs to be created.
  
if(prev.right == null){ // if we have no nodes to right.
prev.right = temp; // here see when we reach end of .right attribute a link is created backwards to the current node.
temp = temp.left; // and now temp is free to go and traverse the remaining left subtree of the BST.
}
else {
// now that we have taken the care of inorder successor backlinks we can now unlink them one by one
// and while we unlink we will keep our count to reach (k) as per requirement.
prev.right = null; // link broken
count++; // as we reached the next successor of inorder traversal. and count is incremented.
if (count == k) // return the value if count == k else continue breaking links.
return temp.key;
temp = temp.right; // update the current variable to the right subtree where it has to search next after root.
}
}

}

Add a comment
Know the answer?
Add Answer to:
In Java Language Please use: (do not change this part) public int kSmallest(Node root, int k){...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a function int levelSearch(Node* root, int key) that takes as input the root node of...

    Write a function int levelSearch(Node* root, int key) that takes as input the root node of a Binary Search tree and a key. The function searches the key in the BST and returns the level of the found node. If the key is not found in the tree, return -1. The level starts at 0 for the root node and increases from top to bottom. We have defined the following node C++ Node class for you: class Node { public:         ...

  • The code is in JAVA public class CheckBST {   //method to implement public static boolean isValidBST(TreeNode...

    The code is in JAVA public class CheckBST {   //method to implement public static boolean isValidBST(TreeNode root) { } public static void main(String[] args) { TreeNode a = new TreeNode(1); TreeNode b = new TreeNode(2); TreeNode c = new TreeNode(3); a.left = b; a.right = c; System.out.println(isValidBST(a)); TreeNode d = new TreeNode(2); TreeNode e = new TreeNode(1); TreeNode f = new TreeNode(3); d.left = e; d.right = f; System.out.println(isValidBST(d)); } } TreeNode.java class TreeNode { int val; TreeNode left; TreeNode...

  • Question B1 You are given the following Java classes: public class Queue { private static class...

    Question B1 You are given the following Java classes: public class Queue { private static class Node { Object object; Node next; Node () { object = null; next = null; } Node (Object object, Node next) { this.object = object; this.next = next; private Node header; private int size = 0; // size shows the no of elements in queue public Object dequeue () { if (size == 0 ) { return null; else { Object remove_object = header.object;...

  • Would appreciate the answer in the Java coding language please and thank you! 10d 10h left...

    Would appreciate the answer in the Java coding language please and thank you! 10d 10h left Java 7 1. Check the Structure Autocomplete Ready 1 > import java.io.*;... 10 ALL A binary tree uses a multi-node data structure where each node may have 0 to 2 child nodes, and has one stored value, its node number in this case. A tree may either be: 11 class Result { * Complete the 'isValid' function below. • An empty tree, the root...

  • Coding Language: C++ Function Header: vector<vector<int>> printFromButtom(TreeNode* root) {} Definition for a binary tree node: struct...

    Coding Language: C++ Function Header: vector<vector<int>> printFromButtom(TreeNode* root) {} Definition for a binary tree node: struct TreeNode { int val; TreeNode *left; TreeNode *right; }; The Problem Complete the printFromButtom function that accepts a BST TreeNode and returns the nodes' value from left to right, level by level from leaf to root. This function will return vector<vector int which similar to a 2-D array. Function std: reverse (myvector.begin myVector en might be helpful. Definition for a binary tree node: struct...

  • Using the following implementation of Tree class Node   {   public int iData;              // data item (key)   public...

    Using the following implementation of Tree class Node   {   public int iData;              // data item (key)   public double dData;           // data item   public Node leftChild;         // this node's left child   public Node rightChild;        // this node's right child   public void displayNode()      // display ourself      {      System.out.print('{');      System.out.print(iData);      System.out.print(", ");      System.out.print(dData);      System.out.print("} ");      }   }  // end class Node //------------------------------------------------------------------ import java.io.IOException; import java.util.Stack; public class Tree { private Node root; // first node of tree // ------------------------------------------------------------- public Tree() // constructor { root = null; }...

  • using java to write,show me the output. please write some common. You CAN NOT use inbuild...

    using java to write,show me the output. please write some common. You CAN NOT use inbuild functions for Tree ADT operations. using code below to finsih public class Main {    public static void main(String[] args) {        BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.left.left.left = new Node(8); tree.root.left.left .right= new Node(9);...

  • In this assignment, you will add several methods to the Binary Search Tree. You should have compl...

    In this assignment, you will add several methods to the Binary Search Tree. You should have completed the following three methods in the lab: public void insert(Key key, Value value) public Value get(Key key) public void inorder(Node root) For this assignment, you will implement the following: public void remove(Node root, Key key) public Key getMin(Node n) public Key getMax(Node n) public int height(Node n) The main method contains the statements to check whether your implementation works. You need to change...

  • Please help me with me. I did the first part to write the operations but in...

    Please help me with me. I did the first part to write the operations but in the driver its shows me errors, can't fix it. Help me. Need help with this to run the application. /** * BinaryTreeNode represents a node in a binary tree with a left and * right child. * * @author Java Foundations * @version 4.0 */ public class BinaryTreeNode { protected T element; protected BinaryTreeNode left, right; /** * Creates a new tree node with...

  • *****************************In Java***************************************In Java***********************************In Java************************* In this problem, you will implement various algorithms operating on binary search...

    *****************************In Java***************************************In Java***********************************In Java************************* In this problem, you will implement various algorithms operating on binary search trees. We have provided with you a standard implementation of a generic BST in BinarySearchTree.java. Note that this class is an abstract class, which means that some of its methods are not implemented. In previous assignments, you have implemented interfaces which specified methods that you needed to write. Very similarly, an abstract class is a class with some unimplemented methods (it can be thought...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT