题目1467:二叉排序树 (非递归与递归)


//非递归实现二叉排序树
#include<iostream>

using namespace std;

struct Node{
	Node *lchild;  //做孩子
	Node *rchild; //右孩子
	int value;
};

//创建节点
void createNode(Node *&p, int x)
{
	Node *root = p;
	Node *pre;

	//创建根节点
	if(root == NULL)
	{
		p = new Node;
		p ->lchild = p ->rchild = NULL;
		p ->value = x;
		cout << "-1" << endl;
	}
	else
	{
		//找到最终的pre节点
		while(root)
		{
			pre = root;
			if(x < root->value)
			{
				root = root->lchild;
			}
			else
			{
				root = root ->rchild;
			}
		}
		//生成新的节点
		root = new Node;
		root ->lchild = root ->rchild = NULL;
		root ->value = x;
		
		//以左或右节点插入
		if(x < pre->value)
		{
			pre ->lchild = root;
		}
		else
			pre->rchild = root;
		cout << pre ->value  << endl;
	}
}


int main()
{
	int N;//记录几组测试数据
	int tmp;

	while(cin >> N)
	{
		Node *p = NULL;
		for(int i= 0; i< N; i++)
		{
			cin >>tmp;
			createNode(p,tmp);
		}
	}
	return 0;
}

//递归形式
#include<iostream>
using namespace std;
#include<stdio.h>
 
class Node
{
public:
    Node(int _value):value(_value){
        lchild = rchild = NULL;
    }
    Node(){
        Node(0);
    }
 
    int value;
    Node *lchild;
    Node *rchild;
};
 
int arr[101];
 
int N;//记录节点数
Node *findTree(Node *root , int x)
{
    if(x < root ->value)
    {
        if(root ->lchild)
        {
            return findTree(root->lchild, x);
        }
        else
        {
            Node *newNode = new Node(x);
            root ->lchild = newNode;
            return root;
        }
    }
    else
    {
        if(root ->rchild)
        {
            return findTree(root ->rchild,x);
        }
        else
        {
            Node* newNode = new Node(x);
            root ->rchild = newNode;
            return root;
        }
    }
}
 
void bulidTree()
{
    Node *root = new Node(arr[0]);
    cout << -1 << endl;
    for(int i =1 ; i<N; i++)
    {
        Node *father = findTree(root,arr[i]);
        cout << father ->value << endl;
    }
}
 
int main()
{
    while(cin >> N)
    {
        for(int i =0; i< N; i++)
        {
            cin >> arr[i];
        }
        bulidTree();
    }
 
    return 0;
}
/**************************************************************
    Problem: 1467
    User: itswyy
    Language: C++
    Result: Accepted
    Time:20 ms
    Memory:1520 kb
****************************************************************/


注:递归情况借鉴 http://www.cnblogs.com/xinsheng/p/3587100.html



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值