类实现之二叉树

#include <stdio.h>
#include <queue>
using namespace std;
class Node
{
public:
    Node* father;
    int num;
    Node* left;
    Node* right;
    Node()
    {
       father=NULL;
       left=NULL;
       right=NULL;
    }

    Node(int num):num(num)
    {
       father=NULL;
       left=NULL;
       right=NULL;
    }

    ~Node()
    {

    }
};
class DTree
{
public:
    Node* proot;
    DTree()
    {
        proot=NULL;
    }
    ~DTree()
    {

    }

    void GetFather(Node* pNode)
    {

        do
        {
            printf("%d\n",pNode->num);
            pNode=pNode->father;
        }while(pNode!=NULL);
    }

    void DFS(Node* pNode)
    {
        printf("%d\n",pNode->num);
        if(pNode->left!=NULL) DFS(pNode->left);
        if(pNode->right!=NULL) DFS(pNode->right);
    }

    void BFS(Node* pNode)
    {
        queue<Node*> q;
        q.push(pNode);
        while(q.size()>0)
        {
            Node* pcur=q.front();
            q.pop();
            printf("%d\n",pcur->num);
            if(pcur->left!=NULL) q.push(pcur->left);
            if(pcur->right!=NULL)  q.push(pcur->right);
        }
    }
};

int main()
{
    Node root(0);
    Node l(1); l.father=&root;  root.left=&l;
        Node ll(3); ll.father=&l;  l.left=&ll;
        Node lr(4); lr.father=&l;  l.right=&lr;
    Node r(2); r.father=&root;  root.right=&r;
        Node rl(5); rl.father=&r;  r.left=&rl;
        Node rr(6); rr.father=&r;  r.right=&rr;
    DTree tree;
    tree.proot=&root;
    tree.GetFather(&lr);
    printf("\n");
    tree.DFS(&root);
    printf("\n");
    tree.BFS(&root);
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值