Question

write the method that return the kth smallest item in the binary search tree. for example...

write the method that return the kth smallest item in the binary search tree. for example if the tree has 18 node and the user enter 13 then the method should return the 13 smallest element in the tree. I has a method that done it recursively but I want to Implement findKth nonrecursively

public String findKth( String k )
{ return findKth( k, root).data; }
public Node findKth(int k, Node t ) {
  
     
   if( t == null )
   throw new IllegalArgumentException( );
   int leftSize = ( t.left != null ) ? ( t.left).size() : 0;

   if( k <= leftSize )
   return findKth( k, t );
   if( k == leftSize + 1 )
   return t;
   return findKth( k - leftSize - 1, t.right );
   }

I appreciate any help :)

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

Answer:

We can inorder traverse the tree and get the kth smallest element in O(n) time.

public int findKth(Node root, int k) {
    Stack<Node> stack = new Stack<Node>();
 
    Node p = root;
    int result = 0;
 
    while(!stack.isEmpty() || p!=null){
        if(p!=null){
            stack.push(p);
            p = p.left;
        }else{
            Node t = stack.pop();
            k--;
            if(k==0)
                result = t.val;
            p = t.right;
        }
    }
 
    return result;
}

Please give thumbsup, if you like it. Thanks.

Add a comment
Know the answer?
Add Answer to:
write the method that return the kth smallest item in the binary search tree. for example...
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
  • Add a non-recursive inorder() method to class LinkedBinaryTree<E> to traverse binary tree. Test inorder() method. Implementation...

    Add a non-recursive inorder() method to class LinkedBinaryTree<E> to traverse binary tree. Test inorder() method. Implementation in Java #########LinkedBinary Tree class######### public class LinkedBinaryTree<E> extends AbstractBinaryTree<E> { //---------------- nested Node class ---------------- /** Nested static class for a binary tree node. */ protected static class Node<E> implements Position<E> { private E element; // an element stored at this node private Node<E> parent; // a reference to the parent node (if any) private Node<E> left; // a reference to the left...

  • Return a method as an expression tree Hi guys. I need to return a method as...

    Return a method as an expression tree Hi guys. I need to return a method as an expression tree, it's currently returning null. public static ExpressionTree getExpressionTree(String expression) throws Exception {       char[] charArray = expression.toCharArray(); Node root = et.constructTree(charArray); System.out.println("infix expression is"); et.inorder(root); return et; } In the above method, et needs to have a value. -- Take a look at the complete class below. Kindly assist. ; public class ExpressionTree extends BinaryTree { private static final String DELIMITERS...

  • Hello. I have written the following function to remove a value from a Binary Search Tree using re...

    Hello. I have written the following function to remove a value from a Binary Search Tree using resources my professors gave and stuff I found online. The problem is I don't know how it works and I need to know how it works to finish the rest of the project. public boolean remove(T value){ if(value == null) return false; class RemoveBSTObj{ private boolean found = false; private Node removeBST(Node root, T value){ if(root == null) return root; //IF there is...

  • Java : This function is to search through a binary tree left and right and return...

    Java : This function is to search through a binary tree left and right and return a count of the nodes above depth k. This is what I have so far, but I'm getting a Null pointer exception. public class MyIntSET {    private Node root;    private static class Node {        public final int key;        public Node left, right;        public Node(int key) { this.key = key; }    }    public int sizeAboveDepth(int...

  • 1) Extend the Binary Search Tree ADT to include a public method leafCount that returns the...

    1) Extend the Binary Search Tree ADT to include a public method leafCount that returns the number of leaf nodes in the tree. 2) Extend the Binary Search Tree ADT to include a public method singleParent-Count that returns the number of nodes in the tree that have only one child. 3) The Binary search tree ADT is extended to include a boolean method similarTrees that receives references to two binary trees and determines whether the shapes of the trees are...

  • 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 I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to com...

    Please I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to completely test every method in the BST class to ensure the class meets all its requirements. You should read the Listing 25.5: TestBST.java for an idea of what your program should look like. Listing 25.4 BST.java public class BST> extends AbstractTree { protected TreeNode...

  • IN JAVA 2 A Binary Search Tree The goal of this lab is to gain familiarity...

    IN JAVA 2 A Binary Search Tree The goal of this lab is to gain familiarity with simple binary search trees. 1. Begin this lab by implementing a simple class that represents a "node” in a binary search tree, as follows. public class MyTreeNode<t extends Comparable<T>> { public T data; public MyTreeNode<T> leftchild; public MyTreeNode<T> rightChild; public MyTreeNode<T> parent; 2. Have the second member of your pair type in the code for the simple binary search tree interface. public interface...

  • Binary Search Tree Part A: The code attached in this document is a sample code to demonstrate ins...

    Binary Search Tree Part A: The code attached in this document is a sample code to demonstrate insert operation in binary search tree. Please fill in the missing part for the insert method to make the program work. The expected output should be as follows. 20 30 40 50 60 70 80 Part B: Find Lowest Common Ancestor (LCA) of a Binary Search Tree. According to WikiPedia definition , The lowest common ancestor is defined between two nodes v and...

  • Java eclipse question. Given a binary search tree -------------M ---------G ---------N ------D----- H ---B----F How woul...

    Java eclipse question. Given a binary search tree -------------M ---------G ---------N ------D----- H ---B----F How would you find the farthest from the root and most right side of the node? So, in this case, farthest nodes are B and F with height of 4 But the most right side of the node is F Therefore answer is F. I have //Will call helper method. public T findRightmostLowest(){ int lv = height();//This is the maxium height of the tree(4 in this...

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