ZOJ 1700 Falling Leaves 二叉搜索树+前序遍历

因为二叉搜索树每次插入的时候都是插入到树的最低端。

所以第一层叶子就是二叉搜索树最后一次插入的内容,第二层叶子是倒数第二次插入的内容.....

所以只需要把输入的内容倒过来建树就行了。

代码如下:

#include <cstdio>
#include <cstdlib>
#include <iostream>

using namespace std;

//节点类
struct Node
{
    char c;
    Node *lchild, *rchild;

    Node()
    {
        lchild = rchild = NULL;
    }
};

/**************************************************
功能: 在根节点指针为root的二叉搜索树中插入ch,
      并返回插入后根节点的指针。
***************************************************/
Node* Insert(Node* root, char ch)
{
    if (root == NULL)
    {
        Node* t = new Node();
        t->c = ch;
        return t;
    }
    else
    {
        if (ch < root->c)
            root->lchild = Insert(root->lchild, ch);
        else root->rchild = Insert(root->rchild, ch);
        return root;
    }
}

/*******************************************
功能: 前序遍历根节点指针为root的这棵树
********************************************/
void preorder(Node* root)
{
    printf("%c", root->c);
    if (root->lchild)
        preorder(root->lchild);
    if (root->rchild)
        preorder(root->rchild);
}

int main()
{
    //freopen("1.txt", "r", stdin);
    int over = 0;
    while (1)
    {
        string s;
        while (1)
        {
            string t;
            cin >> t;
            if (t == "*")
                break;
            else if (t == "$")
            {
                over = 1;
                break;
            }
            s += t;
        }

        int len = s.length();
        Node* root = NULL;
        for (int i = len - 1; i >= 0; i--)
            root = Insert(root, s[i]);

        preorder(root);
        printf("\n");

        if (over)
            break;
    }
    return 0;
}

.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值