In Order Successor in Binary Search Tree

前端 未结 17 1838
孤独总比滥情好
孤独总比滥情好 2020-11-27 04:11

Given a node in a BST, how does one find the next higher key?

17条回答
  •  一生所求
    2020-11-27 04:47

    Node successor(int data) {
      return successor(root, data);
    }
    
    // look for the successor to data in the tree rooted at curr
    private Node successor(Node curr, int data) {
      if (curr == null) {
        return null;
      } else if (data < curr.data) {
        Node suc = successor(curr.left, data);
        // if a successor is found use it otherwise we know this node
        // is the successor since the target node was in this nodes left subtree
        return suc == null ? curr : suc;
      } else if (data > curr.data) {
        return successor(curr.right, data);
      } else {
        // we found the node so the successor might be the min of the right subtree
        return findMin(curr.right);
      }
    }
    
    private Node findMin(Node curr) {
      if (curr == null) {
        return null;
      }
    
      while (curr.left != null) {
        curr = curr.left;
      }
    
      return curr;
    }
    

提交回复
热议问题