• Data Structure Binary Search Tree: Inorder Successor in Binary Search Tree


     1 struct node {
     2     int val;
     3     node *left;
     4     node *right;
     5     node *parent;
     6     node() : val(0), left(NULL), right(NULL) { }
     7     node(int v) : val(v), left(NULL), right(NULL) { }
     8 };
     9 
    10 node* insert(int n, node *root) {
    11     if (root == NULL) {
    12         root = new node(n);
    13         return root;
    14     }
    15     if (n < root->val) {
    16         if (root->left == NULL) {
    17             root->left = new node(n);
    18             return root->left;
    19         }
    20         else return insert(n, root->left);
    21     }
    22     if (n > root->val) {
    23         if (root->right == NULL) {
    24             root->right = new node(n);
    25             return root->right;
    26         }
    27         else return insert(n, root->right);
    28     }
    29 }
    30 
    31 //Variation: How would you find the sucessor of a node?
    32 node* leftmost(node *n) {
    33     if (n == NULL) return NULL;
    34     while (n->left) n = n->left;
    35     return n;
    36 }
    37 
    38 node* findSuccessor(node* n) {
    39     if (n == NULL) return NULL;
    40     if (!n->parent || n->right) return leftmost(n->right);
    41     else {
    42         while (n->parent && n->parent->right == n) n = n->parent; 
    43         return n->parent;
    44     }
    45 }

     下面是没有parent的代码

     1 node *minvalue(node *root) {
     2     while (root->left) root = root->left;
     3     return root;
     4 }
     5 
     6 node* successor(node *root, node *n) {
     7     if (n->right) return minvalue(n->right);
     8     node *succ = NULL;
     9     while (root) {
    10         if (n->data < root->data) {
    11             succ = root;
    12             root = root->left;
    13         }
    14         else if (n->data > root->data) root = root->right;
    15         else break;
    16     }
    17     return succ;
    18 }
  • 相关阅读:
    Android Lint简介
    免费HTTP数据抓包Fiddler2[4.6.1.2]以及显示中文包内容的方法
    IE6、7下bug
    图表插件
    学习:使用svg
    jQuery Transit
    jQuery基础学习笔记(1)
    HTTP协议详解学习
    html5学习笔记
    html释疑
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/3595500.html
Copyright © 2020-2023  润新知