zoukankan      html  css  js  c++  java
  • 【IT笔试面试题整理】二叉查找树后继节点和前驱节点查找 转

          二叉查找树按照二叉树进行组织。二叉查找树关键字的存储方式总是满足二叉查找树性质:

    设x为二查查找树种一个节点。如果y是x的左子树中的一个节点,那么key[x] >= key[y]。如果y是x的右子树的一个节点,那么key[x] <= key[y]。

    这样对二叉查找树进行中序遍历就可得到书中所有元素的一个非降序排列。

    查找某一个存在节点的前驱和后继。某一个节点x的后继就是大于key[x]的关键字中最小的那个节点,前驱就是小于key[x]的关键字中最大的那个节点。查找二叉前驱和后继节点的算法如下所示:

     1 typedef struct _node
     2 {
     3     struct _node* lchild;
     4     struct _node* rchild;
     5     struct _node* parent;
     6     int data;
     7 }node;        //二叉树结构体定义,是带父节点的哦。
     8 
     9 typedef node* Tree;
    10 
    11 //查找二叉树中关键字最小的节点,返回指向该指针的节点。
    12 Tree iterative_searchTree(Tree root, int k)
    13 {
    14     Tree p = root;
    15     while (p != NULL && k != p->data)
    16     {
    17         if (k < p->data)
    18         {
    19             p = p->lchild;
    20         }
    21         else
    22             p = p->rchild;
    23     }
    24     return p;
    25 }
    26 
    27 Tree Tree_Minmum(Tree root)
    28 {
    29     Tree p = root;
    30     while (p->lchild != NULL)
    31     {
    32         p=p->lchild;
    33     }
    34     return p;
    35 }
    36 
    37 Tree Tree_Maximum(Tree root)
    38 {
    39     Tree p = root;
    40     while (p->rchild != NULL)
    41     {
    42         p=p->rchild;
    43     }
    44     return p;
    45 }
    46 
    47 Tree Tree_Successor(Tree p)
    48 {
    49     while(p->rchild != NULL)
    50     {
    51         return Tree_Minmum(p->rchild);    //一种情况,找该节点右子树中关键字最小的节点。
    52     }
    53     
    54     Tree q = p->parent;
    55     while (q != NULL && p == q->rchild)    //另一种情况,该节点不存在右子树,则寻找该节点最低的公共祖先。
    56     {
    57         p = q;
    58         q = q->parent;
    59     }
    60     return q;
    61 }
    62 
    63 Tree Tree_Presuccessor(Tree p)
    64 {
    65     while (p->lchild != NULL)
    66     {
    67         return Tree_Maximum(p->lchild);    //一种情况,找该节点左子树中关键字最大的节点。
    68     }
    69 
    70     Tree q = p->parent;
    71     while (q != NULL && p == q->lchild)    //另一种情况,该节点不存在左子树,则寻找该节点最低的公共祖先。
    72     {
    73         p = q;
    74         q = q->parent;
    75     }
    76     return q;
    77 }
  • 相关阅读:
    DNNClassifier 深度神经网络 分类器
    浏览器对MP4视频 帧宽度 高度的兼容性
    UnicodeEncodeError:'latin-1' codec can't encode character
    文件夹下 文件计数
    the largest value you actually can transmit between the client and server is determined by the amount of available memory and the size of the communications buffers.
    the “identity” of an object
    广告特征 用户特征
    如果一个维度全覆盖,则有效维度应该对该维度全覆盖
    a high-level neural networks AP
    使用 LDA 挖掘的用户喜好主题
  • 原文地址:https://www.cnblogs.com/WayneZeng/p/3034088.html
Copyright © 2011-2022 走看看