【问题标题】:Smallest element in tree that is bigger than x树中大于 x 的最小元素
【发布时间】:2018-06-11 03:21:33
【问题描述】:

如果我想在树中找到比元素 x 大的最小元素,这是正确的方法吗?

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);
    }
}

我觉得这个解决方案不会检查整个树。

非常感谢您的帮助!

【问题讨论】:

标签: java tree binary-search-tree


【解决方案1】:

如果值不在左边,那么它在右边是不正确的。也许父亲本身就是正确的人。想想一个父亲有 data=6,他的左边儿子 data=4,而他右边的有 data=10。SuccessorOf(5) 应该返回父亲。

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);

【讨论】:

    【解决方案2】:

    您可以使用中序遍历以升序获取元素,如果您找到大于期望的元素,那么您就找到了答案

    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);
    
    }
    

    【讨论】:

      猜你喜欢
      • 2016-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-08
      • 2021-12-21
      相关资源
      最近更新 更多