1. 程式人生 > >二叉搜尋樹的插入 (附例題)

二叉搜尋樹的插入 (附例題)

 二叉搜尋樹的插入操作,其實先從根節點開始從上往下比較,如果比節點的值小,就去與左子樹比較,反之,去有子樹比較。

直到節點為空為止,說明找到插入的位置了。

Search trees are data structures that support dynamic set operations including insert, search, delete and so on. Thus a search tree can be used both as a dictionary and as a priority queue.

Binary search tree is one of fundamental search trees. The keys in a binary search tree are always stored in such a way as to satisfy the following binary search tree property:

  • Let xx be a node in a binary search tree. If yy is a node in the left subtree of xx , then y.key≤x.keyy.key≤x.key . If yy is a node in the right subtree of xx , then x.key≤y.keyx.key≤y.key .

The following figure shows an example of the binary search tree.

For example, keys of nodes which belong to the left sub-tree of the node containing 80 are less than or equal to 80, and keys of nodes which belong to the right sub-tree are more than or equal to 80. The binary search tree property allows us to print out all the keys in the tree in sorted order by an inorder tree walk.

A binary search tree should be implemented in such a way that the binary search tree property continues to hold after modifications by insertions and deletions. A binary search tree can be represented by a linked data structure in which each node is an object. In addition to a key field and satellite data, each node contains fields left

, right, and p that point to the nodes corresponding to its left child, its right child, and its parent, respectively.

To insert a new value vv into a binary search tree TT , we can use the procedure insert as shown in the following pseudo code. The insert procedure is passed a node zz for which z.key=vz.key=v , z.left=NILz.left=NIL , and z.right=NILz.right=NIL . The procedure modifies TT and some of the fields of zz in such a way that zz is inserted into an appropriate position in the tree.

1 insert(T, z)
2     y = NIL // parent of x
3     x = 'the root of T'
4     while x ≠ NIL
5         y = x // set the parent
6         if z.key < x.key
7             x = x.left // move to the left child
8         else 
9             x = x.right // move to the right child
10    z.p = y
11
12    if y == NIL // T is empty
13        'the root of T' = z
14    else if z.key < y.key
15        y.left = z // z is the left child of y
16    else 
17        y.right = z // z is the right child of y

Write a program which performs the following operations to a binary search tree TT .

  • insert kk : Insert a node containing kk as key into TT .
  • print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively.

You should use the above pseudo code to implement the insert operation. TT is empty at the initial state.

Input

In the first line, the number of operations mm is given. In the following mm lines, operations represented by insert kk or print are given.

Output

For each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key.

Constraints

  • The number of operations ≤500,001≤500,001
  • The number of print operations ≤10≤10 .
  • −2,000,000,000≤key≤2,000,000,000−2,000,000,000≤key≤2,000,000,000
  • The height of the binary tree does not exceed 100 if you employ the above pseudo code.
  • The keys in the binary search tree are all different.

Sample Input 1

8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print

Sample Output 1

 1 12 17 20 25 30 88
 30 12 1 20 17 25 88

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.

程式碼如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <malloc.h>
using namespace std;
int n;
struct node
{
    int val;
    node *left,*right;
};
node * root;
//初始化根節點
void init()
{
    root=NULL;
}
//插入操作
void Insert (int temp)
{
    //y表示插入元素的父節點
    node* x=root,*y=NULL;
    node* now=(node *)malloc(sizeof(node));
    now->val=temp;
    now->left=now->right=NULL;
    int flag=0;
    while (x!=NULL)
    {
        y=x;
        x->val>temp? x=x->left:x=x->right;
    }
    y==NULL? root=now:y->val<temp? y->right=now:y->left=now;
}
//前序遍歷
void pretraverse (node * nd)
{
    if(nd==NULL)
        return;
    printf(" %d",nd->val);
    pretraverse (nd->left);
    pretraverse (nd->right);
}
//中序遍歷
void intraverse (node * nd)
{
    if(nd==NULL)
        return;
    intraverse (nd->left);
    printf(" %d",nd->val);
    intraverse (nd->right);
}
//輸出結果
void output ()
{
    intraverse (root);
    printf("\n");
    pretraverse (root);
    printf("\n");
}
int main()
{
    scanf("%d",&n);
    init();
    while (n--)
    {
        char s[10];
        scanf("%s",s);
        if(s[0]=='i')
        {
            int x;
            scanf("%d",&x);
            Insert (x);
        }
        else
            output();
    }
    return 0;
}