版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
二叉树形状
核心代码
//寻找叶子节点都根节点路径并打印出
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;
}