DS二叉树——二叉树之父子结点

题目描述

给定一颗二叉树的逻辑结构,(先序遍历的结果,空树用字符‘0’表示,例如AB0C00D00),建立该二叉树的二叉链式存储结构。

编写程序输出该树的所有叶子结点和它们的父亲结点

输入

第一行输入一个整数t,表示有t个二叉树

第二行起,按照题目表示的输入方法,输入每个二叉树的先序遍历,连续输入t行

输出

第一行按先序遍历,输出第1个示例的叶子节点

第二行输出第1个示例中与叶子相对应的父亲节点

以此类推输出其它示例的结果

样例输入

3
AB0C00D00
AB00C00
ABCD0000EF000

样例输出

C D
B A
B C
A A
D F
C E

#include <iostream>
#include <queue>
using namespace std;

//二叉树的链式存储结构
class Binary_tree_node
{
private:
    char data;                    //数据域
    Binary_tree_node *LeftChild;  //左孩子
    Binary_tree_node *RightChild; //右孩子
public:
    Binary_tree_node() : LeftChild(NULL), RightChild(NULL) {}
    ~Binary_tree_node()
    {
        delete LeftChild;
        delete RightChild;
    }
    friend class Binary_tree;
};

class Binary_tree
{
private:
    Binary_tree_node *Root; //根结点
    int pos;
    string str;
    Binary_tree_node *CreateBinary_tree() //先序建立二叉树
    {
        Binary_tree_node *t;
        char ch;
        ch = str[pos++];    
        if (ch == '0') //结点为空
        {
            t = NULL;
        }
        else //结点不为空
        {
            t = new Binary_tree_node();
            t->data = ch;
            t->LeftChild = CreateBinary_tree();
            t->RightChild = CreateBinary_tree();
        }
        return t;       //返回根结点
    }

    void getLeaf(Binary_tree_node *t, char ch) //获取叶子结点和父亲结点
    {                                           //传入父节点跟父节点对应的值
        if (t != NULL)
        {
            if (!t->LeftChild && !t->RightChild)    //若该结点左右孩子为空,则为叶子结点
            {
                cout << t->data << " ";
                Q.push(ch);
                leaf++;
            }
            getLeaf(t->LeftChild, t->data);
            getLeaf(t->RightChild, t->data);
        }
    }

public:
    int leaf;
    queue<char> Q;  //创建队列Q用于存储叶子结点相对应的父亲节点

    Binary_tree() {}
    ~Binary_tree() {}
    void CreateTree(string tree_array)
    {
        pos = 0;
        leaf = 0;
        str=tree_array;
        Root = CreateBinary_tree();
    }
    void getLeaf()
    {
        getLeaf(Root, Root->data);
    }
};

int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        string str;
        Binary_tree Bt;
        cin >> str;
        Bt.CreateTree(str);
        Bt.getLeaf();   //输出叶子结点
        cout << endl;
        while (!Bt.Q.empty())  //输出叶子相对应的父亲节点
        {
            cout << Bt.Q.front() << " ";
            Bt.Q.pop();
        }
        cout << endl;
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值