📜  二进制搜索树中的有序后继

📅  最后修改于: 2021-05-25 00:06:29             🧑  作者: Mango

在二叉树中,节点的有序后继是二叉树的有序遍历中的下一个节点。对于顺序遍历中的最后一个节点,顺序后继者为NULL。
在二叉搜索树中,也可以将输入节点的有序后继对象定义为最小关键字大于输入节点的关键字的节点。因此,有时重要的是按排序顺序查找下一个节点。

另外,在上述图中,序的8后继是10,序的10后继是12和序的14后继是20。

方法1(使用父指针)
在这种方法中,我们假设每个节点都有一个父指针。
基于输入节点的右子树为空或不为空的情况,该算法分为两种情况。

输入: node,root // node是需要其有序后继者的节点。
输出: succ // succnode的有序后继。

  1. 如果node的右子树不为NULL ,则succ位于右子树中。请执行下列操作。
    转到右侧子树,并在右侧子树中返回键值最小的节点。
  2. 如果节点的右sbtree为NULL,则succ是祖先之一。请执行下列操作。
    使用父指针向上移动,直到看到一个节点,该节点是其父节点的左子节点。这样的节点的父节点是succ

执行:
请注意,以下代码中突出显示了用于查找InOrder后继者的函数(带有灰色背景)。

C
#include 
#include 
 
/* A binary tree node has data,
   the pointer to left child
   and a pointer to right child */
struct node {
    int data;
    struct node* left;
    struct node* right;
    struct node* parent;
};
 
struct node* minValue(struct node* node);
 
struct node* inOrderSuccessor(
    struct node* root,
    struct node* n)
{
    // step 1 of the above algorithm
    if (n->right != NULL)
        return minValue(n->right);
 
    // step 2 of the above algorithm
    struct node* p = n->parent;
    while (p != NULL && n == p->right) {
        n = p;
        p = p->parent;
    }
    return p;
}
 
/* Given a non-empty binary search tree,
    return the minimum data 
    value found in that tree. Note that
    the entire tree does not need
    to be searched. */
struct node* minValue(struct node* node)
{
    struct node* current = node;
 
    /* loop down to find the leftmost leaf */
    while (current->left != NULL) {
        current = current->left;
    }
    return current;
}
 
/* Helper function that allocates a new
    node with the given data and
    NULL left and right pointers. */
struct node* newNode(int data)
{
    struct node* node = (struct node*)
        malloc(sizeof(
            struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    node->parent = NULL;
 
    return (node);
}
 
/* Give a binary search tree and
   a number, inserts a new node with   
    the given number in the correct
    place in the tree. Returns the new
    root pointer which the caller should
    then use (the standard trick to
    avoid using reference parameters). */
struct node* insert(struct node* node,
                    int data)
{
    /* 1. If the tree is empty, return a new,
      single node */
    if (node == NULL)
        return (newNode(data));
    else {
        struct node* temp;
 
        /* 2. Otherwise, recur down the tree */
        if (data <= node->data) {
            temp = insert(node->left, data);
            node->left = temp;
            temp->parent = node;
        }
        else {
            temp = insert(node->right, data);
            node->right = temp;
            temp->parent = node;
        }
 
        /* return the (unchanged) node pointer */
        return node;
    }
}
 
/* Driver program to test above functions*/
int main()
{
    struct node *root = NULL, *temp, *succ, *min;
 
    // creating the tree given in the above diagram
    root = insert(root, 20);
    root = insert(root, 8);
    root = insert(root, 22);
    root = insert(root, 4);
    root = insert(root, 12);
    root = insert(root, 10);
    root = insert(root, 14);
    temp = root->left->right->right;
 
    succ = inOrderSuccessor(root, temp);
    if (succ != NULL)
        printf(
            "\n Inorder Successor of %d is %d ",
            temp->data, succ->data);
    else
        printf("\n Inorder Successor doesn't exit");
 
    getchar();
    return 0;
}


Java
// Java program to find minimum
// value node in Binary Search Tree
 
// A binary tree node
class Node {
 
    int data;
    Node left, right, parent;
 
    Node(int d)
    {
        data = d;
        left = right = parent = null;
    }
}
 
class BinaryTree {
 
    static Node head;
 
    /* Given a binary search tree and a number,
     inserts a new node with the given number in
     the correct place in the tree. Returns the new
     root pointer which the caller should then use
     (the standard trick to avoid using reference
     parameters). */
    Node insert(Node node, int data)
    {
 
        /* 1. If the tree is empty, return a new,    
         single node */
        if (node == null) {
            return (new Node(data));
        }
        else {
 
            Node temp = null;
 
            /* 2. Otherwise, recur down the tree */
            if (data <= node.data) {
                temp = insert(node.left, data);
                node.left = temp;
                temp.parent = node;
            }
            else {
                temp = insert(node.right, data);
                node.right = temp;
                temp.parent = node;
            }
 
            /* return the (unchanged) node pointer */
            return node;
        }
    }
 
    Node inOrderSuccessor(Node root, Node n)
    {
 
        // step 1 of the above algorithm
        if (n.right != null) {
            return minValue(n.right);
        }
 
        // step 2 of the above algorithm
        Node p = n.parent;
        while (p != null && n == p.right) {
            n = p;
            p = p.parent;
        }
        return p;
    }
 
    /* Given a non-empty binary search
       tree, return the minimum data 
       value found in that tree. Note that
       the entire tree does not need
       to be searched. */
    Node minValue(Node node)
    {
        Node current = node;
 
        /* loop down to find the leftmost leaf */
        while (current.left != null) {
            current = current.left;
        }
        return current;
    }
 
    // Driver program to test above functions
    public static void main(String[] args)
    {
        BinaryTree tree = new BinaryTree();
        Node root = null, temp = null, suc = null, min = null;
        root = tree.insert(root, 20);
        root = tree.insert(root, 8);
        root = tree.insert(root, 22);
        root = tree.insert(root, 4);
        root = tree.insert(root, 12);
        root = tree.insert(root, 10);
        root = tree.insert(root, 14);
        temp = root.left.right.right;
        suc = tree.inOrderSuccessor(root, temp);
        if (suc != null) {
            System.out.println(
                "Inorder successor of "
                + temp.data + " is " + suc.data);
        }
        else {
            System.out.println(
                "Inorder successor does not exist");
        }
    }
}
 
// This code has been contributed by Mayank Jaiswal


Python
# Python program to find the inroder successor in a BST
 
# A binary tree node
class Node:
 
    # Constructor to create a new node
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
 
def inOrderSuccessor(n):
     
    # Step 1 of the above algorithm
    if n.right is not None:
        return minValue(n.right)
 
    # Step 2 of the above algorithm
    p = n.parent
    while( p is not None):
        if n != p.right :
            break
        n = p
        p = p.parent
    return p
 
# Given a non-empty binary search tree, return the
# minimum data value found in that tree. Note that the
# entire tree doesn't need to be searched
def minValue(node):
    current = node
 
    # loop down to find the leftmost leaf
    while(current is not None):
        if current.left is None:
            break
        current = current.left
 
    return current
 
 
# Given a binary search tree and a number, inserts a
# new node with the given number in the correct place
# in the tree. Returns the new root pointer which the
# caller should then use( the standard trick to avoid
# using reference parameters)
def insert( node, data):
 
    # 1) If tree is empty then return a new singly node
    if node is None:
        return Node(data)
    else:
        
        # 2) Otherwise, recur down the tree
        if data <= node.data:
            temp = insert(node.left, data)
            node.left = temp
            temp.parent = node
        else:
            temp = insert(node.right, data)
            node.right = temp
            temp.parent = node
         
        # return  the unchanged node pointer
        return node
 
 
# Driver progam to test above function
 
root = None
 
# Creating the tree given in the above diagram
root = insert(root, 20)
root = insert(root, 8);
root = insert(root, 22);
root = insert(root, 4);
root = insert(root, 12);
root = insert(root, 10); 
root = insert(root, 14);   
temp = root.left.right.right
 
succ = inOrderSuccessor( root, temp)
if succ is not None:
    print "\nInorder Successor of % d is % d " \
            %(temp.data, succ.data)
else:
    print "\nInorder Successor doesn't exist"
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)


C#
// C# program to find minimum
// value node in Binary Search Tree
using System;
 
// A binary tree node
public
  class Node
  {
    public
      int data;
    public
      Node left, right, parent;
    public
      Node(int d)
    {
      data = d;
      left = right = parent = null;
    }
  }
 
public class BinaryTree
{
  static Node head;
 
  /* Given a binary search tree and a number,
     inserts a new node with the given number in
     the correct place in the tree. Returns the new
     root pointer which the caller should then use
     (the standard trick to avoid using reference
     parameters). */
  Node insert(Node node, int data)
  {
 
    /* 1. If the tree is empty, return a new,    
         single node */
    if (node == null)
    {
      return (new Node(data));
    }
    else
    {
 
      Node temp = null;
 
      /* 2. Otherwise, recur down the tree */
      if (data <= node.data)
      {
        temp = insert(node.left, data);
        node.left = temp;
        temp.parent = node;
      }
      else
      {
        temp = insert(node.right, data);
        node.right = temp;
        temp.parent = node;
      }
 
      /* return the (unchanged) node pointer */
      return node;
    }
  }
 
  Node inOrderSuccessor(Node root, Node n)
  {
 
    // step 1 of the above algorithm
    if (n.right != null)
    {
      return minValue(n.right);
    }
 
    // step 2 of the above algorithm
    Node p = n.parent;
    while (p != null && n == p.right)
    {
      n = p;
      p = p.parent;
    }
    return p;
  }
 
  /* Given a non-empty binary search
       tree, return the minimum data 
       value found in that tree. Note that
       the entire tree does not need
       to be searched. */
  Node minValue(Node node)
  {
    Node current = node;
 
    /* loop down to find the leftmost leaf */
    while (current.left != null)
    {
      current = current.left;
    }
    return current;
  }
 
  // Driver program to test above functions
  public static void Main(String[] args)
  {
    BinaryTree tree = new BinaryTree();
    Node root = null, temp = null, suc = null, min = null;
    root = tree.insert(root, 20);
    root = tree.insert(root, 8);
    root = tree.insert(root, 22);
    root = tree.insert(root, 4);
    root = tree.insert(root, 12);
    root = tree.insert(root, 10);
    root = tree.insert(root, 14);
    temp = root.left.right.right;
    suc = tree.inOrderSuccessor(root, temp);
    if (suc != null) {
      Console.WriteLine(
        "Inorder successor of "
        + temp.data + " is " + suc.data);
    }
    else {
      Console.WriteLine(
        "Inorder successor does not exist");
    }
  }
}
 
// This code is contributed by aashish1995


C
// C program for above approach
#include 
#include 
 
/* A binary tree node has data,
   the pointer to left child
   and a pointer to right child */
struct node
{
    int data;
    struct node* left;
    struct node* right;
    struct node* parent;
};
 
struct node* minValue(struct node* node);
 
struct node* inOrderSuccessor(
    struct node* root,
    struct node* n)
{
     
    // step 1 of the above algorithm
    if (n->right != NULL)
        return minValue(n->right);
 
    struct node* succ = NULL;
 
    // Start from root and search for
    // successor down the tree
    while (root != NULL)
    {
        if (n->data < root->data)
        {
            succ = root;
            root = root->left;
        }
        else if (n->data > root->data)
            root = root->right;
        else
            break;
    }
 
    return succ;
}
 
/* Given a non-empty binary search tree,
    return the minimum data 
    value found in that tree. Note that
    the entire tree does not need
    to be searched. */
struct node* minValue(struct node* node)
{
    struct node* current = node;
 
    /* loop down to find the leftmost leaf */
    while (current->left != NULL)
    {
        current = current->left;
    }
    return current;
}
 
/* Helper function that allocates a new
    node with the given data and
    NULL left and right pointers. */
struct node* newNode(int data)
{
    struct node* node = (struct node*)
        malloc(sizeof(
            struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    node->parent = NULL;
 
    return (node);
}
 
/* Give a binary search tree and
   a number, inserts a new node with   
    the given number in the correct
    place in the tree. Returns the new
    root pointer which the caller should
    then use (the standard trick to
    avoid using reference parameters). */
struct node* insert(struct node* node,
                    int data)
{
    /* 1. If the tree is empty, return a new,
      single node */
    if (node == NULL)
        return (newNode(data));
    else
    {
        struct node* temp;
 
        /* 2. Otherwise, recur down the tree */
        if (data <= node->data)
        {
            temp = insert(node->left, data);
            node->left = temp;
            temp->parent = node;
        }
        else
        {
            temp = insert(node->right, data);
            node->right = temp;
            temp->parent = node;
        }
 
        /* return the (unchanged) node pointer */
        return node;
    }
}
 
/* Driver program to test above functions*/
int main()
{
    struct node *root = NULL, *temp, *succ, *min;
 
    // creating the tree given in the above diagram
    root = insert(root, 20);
    root = insert(root, 8);
    root = insert(root, 22);
    root = insert(root, 4);
    root = insert(root, 12);
    root = insert(root, 10);
    root = insert(root, 14);
    temp = root->left->right->right;
     
    // Function Call
    succ = inOrderSuccessor(root, temp);
    if (succ != NULL)
        printf(
            "\n Inorder Successor of %d is %d ",
            temp->data, succ->data);
    else
        printf("\n Inorder Successor doesn't exit");
 
    getchar();
    return 0;
}
 
// Thanks to R.Srinivasan for suggesting this method.


Java
// Java program for above approach
class GFG
{
   
/* A binary tree node has data,
   the pointer to left child
   and a pointer to right child */
static class node
{
    int data;
    node left;
    node right;
    node parent;
};
 
static node inOrderSuccessor(
    node root,
    node n)
{
     
    // step 1 of the above algorithm
    if (n.right != null)
        return minValue(n.right);
 
    node succ = null;
 
    // Start from root and search for
    // successor down the tree
    while (root != null)
    {
        if (n.data < root.data)
        {
            succ = root;
            root = root.left;
        }
        else if (n.data > root.data)
            root = root.right;
        else
            break;
    }
    return succ;
}
 
/* Given a non-empty binary search tree,
    return the minimum data 
    value found in that tree. Note that
    the entire tree does not need
    to be searched. */
static node minValue(node node)
{
    node current = node;
 
    /* loop down to find the leftmost leaf */
    while (current.left != null)
    {
        current = current.left;
    }
    return current;
}
 
/* Helper function that allocates a new
    node with the given data and
    null left and right pointers. */
static node newNode(int data)
{
    node node = new node();
    node.data = data;
    node.left = null;
    node.right = null;
    node.parent = null;
 
    return (node);
}
 
/* Give a binary search tree and
   a number, inserts a new node with   
    the given number in the correct
    place in the tree. Returns the new
    root pointer which the caller should
    then use (the standard trick to
    astatic void using reference parameters). */
static  node insert(node node,
                    int data)
{
   
    /* 1. If the tree is empty, return a new,
      single node */
    if (node == null)
        return (newNode(data));
    else
    {
        node temp;
 
        /* 2. Otherwise, recur down the tree */
        if (data <= node.data)
        {
            temp = insert(node.left, data);
            node.left = temp;
            temp.parent = node;
        }
        else
        {
            temp = insert(node.right, data);
            node.right = temp;
            temp.parent = node;
        }
 
        /* return the (unchanged) node pointer */
        return node;
    }
}
 
/* Driver program to test above functions*/
public static void main(String[] args)
{
    node root = null, temp, succ, min;
 
    // creating the tree given in the above diagram
    root = insert(root, 20);
    root = insert(root, 8);
    root = insert(root, 22);
    root = insert(root, 4);
    root = insert(root, 12);
    root = insert(root, 10);
    root = insert(root, 14);
    temp = root.left.right.right;
     
    // Function Call
    succ = inOrderSuccessor(root, temp);
    if (succ != null)
        System.out.printf(
            "\n Inorder Successor of %d is %d ",
            temp.data, succ.data);
    else
        System.out.printf("\n Inorder Successor doesn't exit");
}
}
 
// This code is contributed by gauravrajput1


Python3
# Python program to find
# the inroder successor in a BST
 
# A binary tree node
class Node:
 
    # Constructor to create a new node
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
 
def inOrderSuccessor(root, n):
     
    # Step 1 of the above algorithm
    if n.right is not None:
        return minValue(n.right)
 
    # Step 2 of the above algorithm
    succ=Node(None)
     
     
    while( root):
        if(root.datan.data):
            succ=root
            root=root.left
        else:
            break
    return succ
 
# Given a non-empty binary search tree,
# return the minimum data value
# found in that tree. Note that the
# entire tree doesn't need to be searched
def minValue(node):
    current = node
 
    # loop down to find the leftmost leaf
    while(current is not None):
        if current.left is None:
            break
        current = current.left
 
    return current
 
 
# Given a binary search tree
# and a number, inserts a
# new node with the given
# number in the correct place
# in the tree. Returns the
# new root pointer which the
# caller should then use
# (the standard trick to avoid
# using reference parameters)
def insert( node, data):
 
    # 1) If tree is empty
    # then return a new singly node
    if node is None:
        return Node(data)
    else:
        
        # 2) Otherwise, recur down the tree
        if data <= node.data:
            temp = insert(node.left, data)
            node.left = temp
            temp.parent = node
        else:
            temp = insert(node.right, data)
            node.right = temp
            temp.parent = node
         
        # return  the unchanged node pointer
        return node
 
 
# Driver progam to test above function
if __name__ == "__main__":
    root = None
 
  # Creating the tree given in the above diagram
  root = insert(root, 20)
  root = insert(root, 8);
  root = insert(root, 22);
  root = insert(root, 4);
  root = insert(root, 12);
  root = insert(root, 10); 
  root = insert(root, 14);   
  temp = root.left.right
 
  succ = inOrderSuccessor( root, temp)
  if succ is not None:
      print("Inorder Successor of" ,
               temp.data ,"is" ,succ.data)
  else:
      print("InInorder Successor doesn't exist")


C#
// C# program for above approach
using System;
 
public class GFG
{
 
  /* A binary tree node has data,
   the pointer to left child
   and a pointer to right child */
  public
    class node
    {
      public
        int data;
      public
        node left;
      public
        node right;
      public
        node parent;
    };
 
  static node inOrderSuccessor(
    node root,
    node n)
  {
 
    // step 1 of the above algorithm
    if (n.right != null)
      return minValue(n.right);
 
    node succ = null;
 
    // Start from root and search for
    // successor down the tree
    while (root != null)
    {
      if (n.data < root.data)
      {
        succ = root;
        root = root.left;
      }
      else if (n.data > root.data)
        root = root.right;
      else
        break;
    }
    return succ;
  }
 
  /* Given a non-empty binary search tree,
    return the minimum data 
    value found in that tree. Note that
    the entire tree does not need
    to be searched. */
  static node minValue(node node)
  {
    node current = node;
 
    /* loop down to find the leftmost leaf */
    while (current.left != null)
    {
      current = current.left;
    }
    return current;
  }
 
  /* Helper function that allocates a new
    node with the given data and
    null left and right pointers. */
  static node newNode(int data)
  {
    node node = new node();
    node.data = data;
    node.left = null;
    node.right = null;
    node.parent = null;
 
    return (node);
  }
 
  /* Give a binary search tree and
   a number, inserts a new node with   
    the given number in the correct
    place in the tree. Returns the new
    root pointer which the caller should
    then use (the standard trick to
    astatic void using reference parameters). */
  static  node insert(node node,
                      int data)
  {
 
    /* 1. If the tree is empty, return a new,
      single node */
    if (node == null)
      return (newNode(data));
    else
    {
      node temp;
 
      /* 2. Otherwise, recur down the tree */
      if (data <= node.data)
      {
        temp = insert(node.left, data);
        node.left = temp;
        temp.parent = node;
      }
      else
      {
        temp = insert(node.right, data);
        node.right = temp;
        temp.parent = node;
      }
 
      /* return the (unchanged) node pointer */
      return node;
    }
  }
 
  /* Driver program to test above functions*/
  public static void Main(String[] args)
  {
    node root = null, temp, succ;
 
    // creating the tree given in the above diagram
    root = insert(root, 20);
    root = insert(root, 8);
    root = insert(root, 22);
    root = insert(root, 4);
    root = insert(root, 12);
    root = insert(root, 10);
    root = insert(root, 14);
    temp = root.left.right.right;
 
    // Function Call
    succ = inOrderSuccessor(root, temp);
    if (succ != null)
      Console.Write(
      "\n Inorder Successor of {0} is {1} ",
      temp.data, succ.data);
    else
      Console.Write("\n Inorder Successor doesn't exit");
  }
}
 
// This code is contributed by gauravrajput1


输出
Inorder Successor of 14 is 20

复杂度分析:

  • 时间复杂度: O(h),其中h是树的高度。
    与第二种情况(假设是倾斜的树)一样,我们必须一直朝根方向移动。
  • 辅助空间: O(1)。
    由于不使用任何数据结构来存储值。

方法2(从根目录搜索)
此算法不需要父指针。基于输入节点的右子树为空或不为空的情况,该算法分为两种情况。

输入: node,root //节点是需要其有序后继者的节点。
输出: succ // succnode的有序后继。

  1. 如果node的右子树不为NULL ,则succ位于右子树中。请执行下列操作。
    转到右侧子树,并在右侧子树中返回键值最小的节点。
  2. 如果节点的右子树为NULL,则从根开始并使用类似搜索的技术。请执行下列操作。
    向下移动到树上,如果节点的数据大于根的数据,则转到右侧,否则,转到左侧。

下面是上述方法的实现:

C

// C program for above approach
#include 
#include 
 
/* A binary tree node has data,
   the pointer to left child
   and a pointer to right child */
struct node
{
    int data;
    struct node* left;
    struct node* right;
    struct node* parent;
};
 
struct node* minValue(struct node* node);
 
struct node* inOrderSuccessor(
    struct node* root,
    struct node* n)
{
     
    // step 1 of the above algorithm
    if (n->right != NULL)
        return minValue(n->right);
 
    struct node* succ = NULL;
 
    // Start from root and search for
    // successor down the tree
    while (root != NULL)
    {
        if (n->data < root->data)
        {
            succ = root;
            root = root->left;
        }
        else if (n->data > root->data)
            root = root->right;
        else
            break;
    }
 
    return succ;
}
 
/* Given a non-empty binary search tree,
    return the minimum data 
    value found in that tree. Note that
    the entire tree does not need
    to be searched. */
struct node* minValue(struct node* node)
{
    struct node* current = node;
 
    /* loop down to find the leftmost leaf */
    while (current->left != NULL)
    {
        current = current->left;
    }
    return current;
}
 
/* Helper function that allocates a new
    node with the given data and
    NULL left and right pointers. */
struct node* newNode(int data)
{
    struct node* node = (struct node*)
        malloc(sizeof(
            struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    node->parent = NULL;
 
    return (node);
}
 
/* Give a binary search tree and
   a number, inserts a new node with   
    the given number in the correct
    place in the tree. Returns the new
    root pointer which the caller should
    then use (the standard trick to
    avoid using reference parameters). */
struct node* insert(struct node* node,
                    int data)
{
    /* 1. If the tree is empty, return a new,
      single node */
    if (node == NULL)
        return (newNode(data));
    else
    {
        struct node* temp;
 
        /* 2. Otherwise, recur down the tree */
        if (data <= node->data)
        {
            temp = insert(node->left, data);
            node->left = temp;
            temp->parent = node;
        }
        else
        {
            temp = insert(node->right, data);
            node->right = temp;
            temp->parent = node;
        }
 
        /* return the (unchanged) node pointer */
        return node;
    }
}
 
/* Driver program to test above functions*/
int main()
{
    struct node *root = NULL, *temp, *succ, *min;
 
    // creating the tree given in the above diagram
    root = insert(root, 20);
    root = insert(root, 8);
    root = insert(root, 22);
    root = insert(root, 4);
    root = insert(root, 12);
    root = insert(root, 10);
    root = insert(root, 14);
    temp = root->left->right->right;
     
    // Function Call
    succ = inOrderSuccessor(root, temp);
    if (succ != NULL)
        printf(
            "\n Inorder Successor of %d is %d ",
            temp->data, succ->data);
    else
        printf("\n Inorder Successor doesn't exit");
 
    getchar();
    return 0;
}
 
// Thanks to R.Srinivasan for suggesting this method.

Java

// Java program for above approach
class GFG
{
   
/* A binary tree node has data,
   the pointer to left child
   and a pointer to right child */
static class node
{
    int data;
    node left;
    node right;
    node parent;
};
 
static node inOrderSuccessor(
    node root,
    node n)
{
     
    // step 1 of the above algorithm
    if (n.right != null)
        return minValue(n.right);
 
    node succ = null;
 
    // Start from root and search for
    // successor down the tree
    while (root != null)
    {
        if (n.data < root.data)
        {
            succ = root;
            root = root.left;
        }
        else if (n.data > root.data)
            root = root.right;
        else
            break;
    }
    return succ;
}
 
/* Given a non-empty binary search tree,
    return the minimum data 
    value found in that tree. Note that
    the entire tree does not need
    to be searched. */
static node minValue(node node)
{
    node current = node;
 
    /* loop down to find the leftmost leaf */
    while (current.left != null)
    {
        current = current.left;
    }
    return current;
}
 
/* Helper function that allocates a new
    node with the given data and
    null left and right pointers. */
static node newNode(int data)
{
    node node = new node();
    node.data = data;
    node.left = null;
    node.right = null;
    node.parent = null;
 
    return (node);
}
 
/* Give a binary search tree and
   a number, inserts a new node with   
    the given number in the correct
    place in the tree. Returns the new
    root pointer which the caller should
    then use (the standard trick to
    astatic void using reference parameters). */
static  node insert(node node,
                    int data)
{
   
    /* 1. If the tree is empty, return a new,
      single node */
    if (node == null)
        return (newNode(data));
    else
    {
        node temp;
 
        /* 2. Otherwise, recur down the tree */
        if (data <= node.data)
        {
            temp = insert(node.left, data);
            node.left = temp;
            temp.parent = node;
        }
        else
        {
            temp = insert(node.right, data);
            node.right = temp;
            temp.parent = node;
        }
 
        /* return the (unchanged) node pointer */
        return node;
    }
}
 
/* Driver program to test above functions*/
public static void main(String[] args)
{
    node root = null, temp, succ, min;
 
    // creating the tree given in the above diagram
    root = insert(root, 20);
    root = insert(root, 8);
    root = insert(root, 22);
    root = insert(root, 4);
    root = insert(root, 12);
    root = insert(root, 10);
    root = insert(root, 14);
    temp = root.left.right.right;
     
    // Function Call
    succ = inOrderSuccessor(root, temp);
    if (succ != null)
        System.out.printf(
            "\n Inorder Successor of %d is %d ",
            temp.data, succ.data);
    else
        System.out.printf("\n Inorder Successor doesn't exit");
}
}
 
// This code is contributed by gauravrajput1

Python3

# Python program to find
# the inroder successor in a BST
 
# A binary tree node
class Node:
 
    # Constructor to create a new node
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
 
def inOrderSuccessor(root, n):
     
    # Step 1 of the above algorithm
    if n.right is not None:
        return minValue(n.right)
 
    # Step 2 of the above algorithm
    succ=Node(None)
     
     
    while( root):
        if(root.datan.data):
            succ=root
            root=root.left
        else:
            break
    return succ
 
# Given a non-empty binary search tree,
# return the minimum data value
# found in that tree. Note that the
# entire tree doesn't need to be searched
def minValue(node):
    current = node
 
    # loop down to find the leftmost leaf
    while(current is not None):
        if current.left is None:
            break
        current = current.left
 
    return current
 
 
# Given a binary search tree
# and a number, inserts a
# new node with the given
# number in the correct place
# in the tree. Returns the
# new root pointer which the
# caller should then use
# (the standard trick to avoid
# using reference parameters)
def insert( node, data):
 
    # 1) If tree is empty
    # then return a new singly node
    if node is None:
        return Node(data)
    else:
        
        # 2) Otherwise, recur down the tree
        if data <= node.data:
            temp = insert(node.left, data)
            node.left = temp
            temp.parent = node
        else:
            temp = insert(node.right, data)
            node.right = temp
            temp.parent = node
         
        # return  the unchanged node pointer
        return node
 
 
# Driver progam to test above function
if __name__ == "__main__":
    root = None
 
  # Creating the tree given in the above diagram
  root = insert(root, 20)
  root = insert(root, 8);
  root = insert(root, 22);
  root = insert(root, 4);
  root = insert(root, 12);
  root = insert(root, 10); 
  root = insert(root, 14);   
  temp = root.left.right
 
  succ = inOrderSuccessor( root, temp)
  if succ is not None:
      print("Inorder Successor of" ,
               temp.data ,"is" ,succ.data)
  else:
      print("InInorder Successor doesn't exist")

C#

// C# program for above approach
using System;
 
public class GFG
{
 
  /* A binary tree node has data,
   the pointer to left child
   and a pointer to right child */
  public
    class node
    {
      public
        int data;
      public
        node left;
      public
        node right;
      public
        node parent;
    };
 
  static node inOrderSuccessor(
    node root,
    node n)
  {
 
    // step 1 of the above algorithm
    if (n.right != null)
      return minValue(n.right);
 
    node succ = null;
 
    // Start from root and search for
    // successor down the tree
    while (root != null)
    {
      if (n.data < root.data)
      {
        succ = root;
        root = root.left;
      }
      else if (n.data > root.data)
        root = root.right;
      else
        break;
    }
    return succ;
  }
 
  /* Given a non-empty binary search tree,
    return the minimum data 
    value found in that tree. Note that
    the entire tree does not need
    to be searched. */
  static node minValue(node node)
  {
    node current = node;
 
    /* loop down to find the leftmost leaf */
    while (current.left != null)
    {
      current = current.left;
    }
    return current;
  }
 
  /* Helper function that allocates a new
    node with the given data and
    null left and right pointers. */
  static node newNode(int data)
  {
    node node = new node();
    node.data = data;
    node.left = null;
    node.right = null;
    node.parent = null;
 
    return (node);
  }
 
  /* Give a binary search tree and
   a number, inserts a new node with   
    the given number in the correct
    place in the tree. Returns the new
    root pointer which the caller should
    then use (the standard trick to
    astatic void using reference parameters). */
  static  node insert(node node,
                      int data)
  {
 
    /* 1. If the tree is empty, return a new,
      single node */
    if (node == null)
      return (newNode(data));
    else
    {
      node temp;
 
      /* 2. Otherwise, recur down the tree */
      if (data <= node.data)
      {
        temp = insert(node.left, data);
        node.left = temp;
        temp.parent = node;
      }
      else
      {
        temp = insert(node.right, data);
        node.right = temp;
        temp.parent = node;
      }
 
      /* return the (unchanged) node pointer */
      return node;
    }
  }
 
  /* Driver program to test above functions*/
  public static void Main(String[] args)
  {
    node root = null, temp, succ;
 
    // creating the tree given in the above diagram
    root = insert(root, 20);
    root = insert(root, 8);
    root = insert(root, 22);
    root = insert(root, 4);
    root = insert(root, 12);
    root = insert(root, 10);
    root = insert(root, 14);
    temp = root.left.right.right;
 
    // Function Call
    succ = inOrderSuccessor(root, temp);
    if (succ != null)
      Console.Write(
      "\n Inorder Successor of {0} is {1} ",
      temp.data, succ.data);
    else
      Console.Write("\n Inorder Successor doesn't exit");
  }
}
 
// This code is contributed by gauravrajput1
输出
Inorder Successor of 14 is 20

复杂度分析:

  • 时间复杂度: O(h),其中h是树的高度。
    如上所述,在最坏的情况下,我们会移动树的整个高度
  • 辅助空间: O(1)。
    由于不使用任何数据结构来存储值。