简体   繁体   中英

Recursive inorder Successor of a given element in BST with java

Because the code is too long the link is here -> http://pastebin.com/jXgbE6bB Because i am not that good at recursions i just can't find the right recursion function for this problem.
(PSI am new to this forum and i know i am going to have a lot of hate comments like why not go find tutorials on recursions and other things,but believe me i have done everything but i just can't understand the logic of the recursions)
My question is What's the recursive function for in-order successor of a given element in Binary search tree?
I made it this far but it just returns the parent of the node it's supposed to print:

public E getSuccessor(BNode<E> t, E x) {
    if(t.left!=null && x.equals(t.info)){
        return t.left.info;
    }
    else if(x.compareTo(t.info)<0){
        return (getSuccessor(t.left, x));
    }
    else {
        return (getSuccessor(t.right, x));
    }
}

public E getSuccessor(E x) {
    return getSuccessor(root, x);
}

The inorder successor of a given node is the lowest node in the right subtree of that node. To understand otherwise, it is the next node that will be printed in a simple in order traversal of the tree.

  1. If the node has a right child, this solution is simplified to finding the smallest node in the right subtree.
  2. If the node doesn't have a right child, and there are no parent pointers, we need to start from the root of the tree and work our way to identify this successor.

Here is the recursive way to solve this. While calling the method, pass root as the root of the tree, the node who's successor is needed as t and null as the successor because the method will calculate it. Something like the following -

BinaryTreeNode successor=tree.inorderSuccessor(root,node,null);

public BinaryTreeNode<Type> inorderSuccessor(BinaryTreeNode<Type> root,BinaryTreeNode<Type> t,BinaryTreeNode<Type> successor)
{
    if(root==null)
        return null;
    if(root.element==t.element)
    {
        if(root.right!=null)
            return findMin(root.right);
        else
            return successor;
    }
    int cmp=t.element.compareTo(root.element);

    if(cmp < 0)
        return inorderSuccessor(root.left,t,root);
    else
        return inorderSuccessor(root.right,t,successor);
}

public BinaryTreeNode<Type> findMin(BinaryTreeNode<Type> t)
{
    if(t==null)
        return t;
    while(t.left!=null)
        t=t.left;
    return t;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM