C++二叉树寻找叶子节点到根节点的路径

二叉树形状

在这里插入图片描述

核心代码

//寻找叶子节点都根节点路径并打印出
void PrintAllPath(BTNode *p) {
    if (p) {
        Push(s, *p);
        BTNode x;
        if (p->left == NULL && p->right == NULL) {
            mirror = s;

            while (!StackEmpty(mirror)) {
                GetTop(mirror, x);
                cout << x.val << " ";
                Pop(mirror, x);
            }
            cout << endl;
            Pop(s, x);
        }
        PrintAllPath(p->left);
        PrintAllPath(p->right);
        if (p->left != NULL || p->right != NULL) {
            Pop(s, x);
        }
    }

}

完整代码

#include <iostream>

using namespace std;
#define MaxSize 50

struct BTNode {
    int val;
    BTNode *left;
    BTNode *right;

    BTNode(int x = 0) : val(x), left(NULL), right(NULL) {}
};


//定义栈
struct SqStack {
    BTNode data[MaxSize];
    int top;
};

SqStack s, mirror;

//栈相关操作
//初始化
void InitStack(SqStack &s) {
    s.top = -1;
}

//栈判空
bool StackEmpty(SqStack s) {
    if (s.top == -1) {
        return true;
    } else {
        return false;
    }
}

//进栈
bool Push(SqStack &s, BTNode x) {
    if (s.top == MaxSize - 1) {
        return false;
    }
    s.data[++s.top] = x;
    return true;
}

//出栈
bool Pop(SqStack &s, BTNode &x) {
    if (s.top == -1) {
        return false;
    }
    x = s.data[s.top--];
    return true;
}

//读取栈顶元素
bool GetTop(SqStack s, BTNode &x) {
    if (s.top == -1) {
        return false;
    }
    x = s.data[s.top];
    return true;
}


//寻找叶子节点都根节点路径并打印出
void PrintAllPath(BTNode *p) {
    if (p) {
        Push(s, *p);
        BTNode x;
        if (p->left == NULL && p->right == NULL) {
            mirror = s;

            while (!StackEmpty(mirror)) {
                GetTop(mirror, x);
                cout << x.val << " ";
                Pop(mirror, x);
            }
            cout << endl;
            Pop(s, x);
        }
        PrintAllPath(p->left);
        PrintAllPath(p->right);
        if (p->left != NULL || p->right != NULL) {
            Pop(s, x);
        }
    }

}


int main() {
    //构造二叉树
    BTNode *p;
    BTNode b0(0);
    BTNode b1(1);
    BTNode b2(2);
    BTNode b3(3);
    BTNode b4(4);
    BTNode b5(5);
    BTNode b6(6);
    BTNode b7(7);
    BTNode b8(8);
    BTNode b9(9);
    BTNode b10(10);
    BTNode b13(13);
    BTNode b15(15);

    b0.left = &b1;
    b0.right = &b2;
    b1.left = &b3;
    b1.right = &b4;
    b2.left = &b5;
    b2.right = &b6;
    b3.left = &b7;
    b3.right = &b8;
    b4.left = &b9;
    b4.right = &b10;
    b6.left = &b13;
    b13.left = &b15;


    p = &b0;

    //初始化栈
    InitStack(s);

    //调用核心算法
    PrintAllPath(p);


    return 0;
}

输出结果

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值