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

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<string>
using namespace std;

class BiTreeNode {
public:
    char data;
    BiTreeNode *LeftChild;
    BiTreeNode *RightChild;
    BiTreeNode *Parent;
    BiTreeNode():LeftChild(NULL),RightChild(NULL),Parent(NULL){}
};

class BiTree {
public:
    void CreateTree(string s);
    void FindLeaves();
    void FindParent();
private:
    BiTreeNode *CreateTree();
    void FindLeaves(BiTreeNode *t);
    void FindParent(BiTreeNode *t);
    int len;
    int pos;
    string strTree;
    BiTreeNode *Root;
};

void BiTree::FindParent()
{
    FindParent(Root);
}

void BiTree::FindParent(BiTreeNode *t)
{
    if(t)
    {
        if(t->LeftChild)
            FindParent(t->LeftChild);
        if(t->RightChild)
            FindParent(t->RightChild);
        if(t->LeftChild == NULL  && t->RightChild == NULL)
            cout<<t->Parent->data<<" ";
    }
}

void BiTree::FindLeaves()
{
    FindLeaves(Root);
}

void BiTree::FindLeaves(BiTreeNode *t)
{
    if(t)
    {
        if(t->LeftChild)
            FindLeaves(t->LeftChild);
        if(t->RightChild)
            FindLeaves(t->RightChild);
        if(t->LeftChild==NULL&&t->RightChild == NULL)
            cout<<t->data<<" ";
    }
}

void BiTree::CreateTree(string s)
{
    len = 0;
    pos = 0;
    strTree.assign(s);
    Root = CreateTree();
}

BiTreeNode *BiTree::CreateTree()
{
    char ch;
    ch = strTree[pos++];
    BiTreeNode *T;
    if(ch == '0')
        T = NULL;
    else
    {
        T = new BiTreeNode();
        T->data = ch;
        T->LeftChild = CreateTree();
        if(T->LeftChild)
            T->LeftChild->Parent = T;
        T->RightChild = CreateTree();
        if(T->RightChild)
            T->RightChild->Parent = T;
    }
    return T;
}

int main()
{
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        string s;
        cin>>s;
        BiTree biTree;
        biTree.CreateTree(s);
        biTree.FindLeaves();
        cout<<endl;
        biTree.FindParent();
        cout<<endl;
    }
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值