二叉树- 二叉搜索树

来源:互联网 发布:it培训评价网 编辑:程序博客网 时间:2024/06/10 03:40

POJ5431 二叉搜索树

主要思路& 关键点:

  • 把新插入的数封装成为结点
  • 层层向下寻找应该插入的位置
  • 注意终止递归的条件 如果我们再中间某个点发现了要往左走可是没有左儿子的时候就应该直接把左儿子赋为cur
  • 而不是想着结合左右两种情况,都搜索到没有儿子停止,这样的话我们没有办法把cur和它的父亲连起来
    代码实现
#include <iostream>using namespace std;struct btn{    int data;    btn *lc, *rc;};void pre_order(btn *root){    if(root)    {        printf("%d ",root->data);        pre_order(root->lc);        pre_order(root->rc);    }}int main(){#ifndef ONLINE_JUDGE    freopen("input.txt", "r", stdin);    freopen("output.txt", "w", stdout);#endif    int tmp;    cin >> tmp;    btn * root = new btn;    root -> data = tmp;    root->lc = NULL, root->rc = NULL;    while(cin >> tmp)    {        btn *cur = new btn;        btn *next = root;        cur->data = tmp;        cur->lc = NULL, cur->rc = NULL;        while(next)        {            if(cur->data == next->data)                break;            if(cur->data < next->data)            {                if(next->lc)                    next = next->lc;                else                {                    next->lc = cur;                    break;                }            }            if(cur->data > next->data)            {                if(next->rc)                    next = next->rc;                else                    {                    next->rc = cur;                    break;                }            }        }    }    pre_order(root);      #ifndef ONLINE_JUDGE    fclose(stdin); fclose(stdout);    #endif}
原创粉丝点击