1

If I want to find the smallest element in a tree that is bigger than an element x, would this be a correct way to do it?

class Node {
   int data;
   Node left, right;
}

Node root;

public Integer successorOf(int x) {
    return successorOf(x, root);
}

private Integer successorOf(int x, Node n) {
    if (n == null) {
        return null;
    }
    if (x < n.data) {
        Integer res = successorOf(x, n.left);
        if (res == null)
            res = n.data;
        return res;
    } else {
        return successorOf(x, n.right);
    }
}

I feel like this solution does not check the entire tree.

Help is much appreciated!

Timothy Truckle
  • 15,071
  • 2
  • 27
  • 51
micro
  • 11
  • 1
  • 4
  • Duplicate of [To find largest element smaller than K in a BST](https://stackoverflow.com/q/6334514) (just need to flip the logic) or [In Order Successor in Binary Search Tree](https://stackoverflow.com/q/5471731) (it's not entirely clear what you're asking). – Bernhard Barker Dec 31 '17 at 17:04

2 Answers2

0

You can use inorder traversal to get the elements in ascending order and if you find an element greater than the desired then you found the answer

private int answer = -1;          // to store the answer

traverse(root,x,0)                // call this method

public void traverse(Node n,int x,int flag){

    if(n == null || flag == 1){   // flag=1 meaning we already found the answer
        return;
    }
    traverse(n.left,x,flag);
    if(n.data>x){                 // smallest value greater than x
        answer=n.data;            // store the answer 
        flag = 1;                 // mark flag = 1, to make subsequent calls 
    }                             // return from the function
    traverse(n.right,x,flag);

}
-1

It's not true that if the value wasn't on the left it's on the right. Maybe it's the father itself the right one. Think about a father that has data=6, his left son data=4 while his right one has data= 10. SuccessorOf(5) should return the father.

private Integer successorOf(int x, Node n) {
   if(n==null)
       return null;
   if(x < node.data){
     if(node.left!= null and node.left.data > x)
        return successorOf(x, node.left);
     else                    
         return node.data;
    }
   else               //x >= n.data
      return successorOf(x, node.right);
Wippo
  • 853
  • 8
  • 22