inorder predecessor bst

Bst inorder successor/ predecessore 
With parent pointer, without parent pointer 
Iterative, recursive 

=======================================
Predecessor with a parent pointer (iterative)


idea: 
cases: 

does this node have a left substree, if yes 
then the largest smaller node is the rightmost node of the node.left
so in this example, 3's predecessor is 2.9
  

if this node doesnt have left subtree, then we want to go up, if
  node.parent.right = node. then the predecessor is the node.parent
   7's predecessor is 6
  
if node.parent.left = node, then we need to go up until node.parent.right = node
 5's predecessor is 4

these sound dry, helps with a picture 

              4
            /   \
          2      6 
        /  \    /\
        1  3    5 7 
          /
        2.8
        /  \
      2.7  2.9



class Node{
  int val;
  Node left;
  Node right;
  Node parent;
  
  // how this is different from not using this. which one is better? 
  // not using this or using this
  // what's the difference between having a constructor with all the values 
  // i've seen sometimes people dont have a construtor, is it okay? 
  
  public Node(int val, Node left, Node right, Node parent){
    this.val = val;
    this.left = left;
    this.right = right;
    this.parent = parent;
  }
  
}

public Node predecessor(Node node){
  if(node == null) return null;
  
  if(node.left != null) return rightMost(node.left);
  
  Node cur = node;
  Node parent = node.parent;
  
  while(parent != null && parent.right != cur){
    cur = parent;
    parent = parent.parent;
  }
  return parent;
}

private Node rightMost(Node node){
  while(node.right != null){
    node = node.right;
  }
  return node;
}

===============================================
Predecessor without  a parent pointer (iterative)


public TreeNode predecessor(TreeNode root, TreeNode node){
  TreeNode result = null;
  while(root != null){
    if(root.val >= node.val){
      root = root.left;
    }else{
      // root.val < node.val
      result = root;
      root = root.right;
    }
  }
  return result;
}


===============================================
Predecessor without  a parent pointer (recursive )

public TreeNode predecessor(TreeNode root, TreeNode node){
  if(root == null) return null;
  if(root.val < node.val){
    TreeNode result = predecessor(root.right, node);
    if(result == null){
      return root;
    }else{
      return result;
    }
  }else{
    return predecessor(root.left, node);
  }
}
   

 

posted on 2018-09-08 04:34  猪猪&#128055;  阅读(251)  评论(0)    收藏  举报

导航