Binary search tree Summary

Build binary search tree

struct node *insert(int k, struct node *T)
{
    if (!T)
    {
        T = new node;
        T->data = k;
        T->l = T->r = NULL;
    }
    else
    {
        if (k > T->data)
            T->r = creat(k, T->r);
        else
            T->l = creat(k, T->l);
    }
    return T;
}

To determine whether the same a binary search tree

How to determine whether the same binary tree? How it is called is a binary tree with it?
For finding binary search tree, the idea is:
1, start looking from the root node, if the tree is empty, it returns NULL.
2, if the tree is not empty, let the root of the data X and Data for comparison.
3, if the value of X is greater than the root node Data, the search proceeds right subtree; if the value of X is less than the root node Data, the search proceeds left subtree.
4, if the value of X is equal Data, says the lookup is completed, the node returns.

第一种方法,两棵树直接递归比较:
核心代码:
void judge(struct node *T, struct node *t)
{
    if (T&&t)
    {
        if (T->data != t->data)
        {
            flag = 1;
            return ;
        }
        judge(T->l, t->l);
        judge(T->r, t->r);
    }
}
第二种方法,循环查找(效率高):
核心代码:
node* judge(int x, node* T)
{
    while(T)
    {
        if(x > T->data)
            T=T->r;
        else if(x < T->data)
            T=T->l;
        else
            return T;
    }
    return NULL;
}

Binary search tree (mirrors) Analyzing

Given a string of numbers, it is determined whether the sequence is a sequence preorder traversal of a tree or a binary search tree mirrored binary search tree, and if so, the subsequent output results preorder

Problem-solving ideas:
1. First is to determine whether the binary search tree, given preorder, so the first number is the root of the first order, the first number greater than or equal to find root node, from this number start right subtree, if there is less than a right subtree of the root node number which is not less binary search tree ; image contrast conditions can be determined node
2, if a binary search tree is a binary tree generated while the recursive side, and finally returns the root node
3, the binary search tree traversal order

To be continued. . .

Published 29 original articles · won praise 4 · Views 4686

Guess you like

Origin blog.csdn.net/onion___/article/details/88831528