【题目来自灰灰考研】
二叉树采用二叉链表进行存储(如下所示),每个结点包含数据域Data,左孩子指针域left和右孩子指针域right。请设计算法给定一颗树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历)。
Typedef struct BitNode{
TElemType data;
struct BitNode *left, *right;
} *BiTree ;
样例
给出一棵二叉树 {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
按照从下往上的层次遍历为:
[ [15,7], [9,20], [3] ]
#include<iostream>
#include<cstdio>
#include<cstdlib>
#define MAXSIZE 20
using namespace std;
typedef struct TNode{
char data;
struct TNode *lChild, *rChild;
}TNode;
TNode *createBTree()
{
//124##57###38#9###
TNode *node;
char data;
cin>>data;
if(data == '#')
return NULL;
else
{
node = (TNode*)malloc(sizeof(TNode));
node->data = data;
node->lChild = createBTree();
node->rChild = createBTree();
}
return node;
}
void reverseLevelVisit(TNode *root)
{
/*
使用层次遍历+栈就可以了
但是注意一点,在正常层序遍历的时候
当遍历到一个节点时,首先将该节点压入栈中
如果其有右孩子节点,先将其右节点入队列,
如果有左孩子节点,再将其左孩子节点入栈,一定不能搞反了
因为只有这样出栈的时候才是从左到右访问的
*/
int front = 0, rear = 0;
TNode *queue[MAXSIZE], *p;
TNode *stack[MAXSIZE];
int top = -1;
rear = (rear + 1) % MAXSIZE;
queue[rear] = root;
while(rear != front)
{
front = (front + 1) % MAXSIZE;
p = queue[front];
stack[++top] = p;
if(p->rChild)
{
rear = (rear + 1) % MAXSIZE;
queue[rear] = p->rChild;
}
if(p->lChild)
{
rear = (rear + 1) % MAXSIZE;
queue[rear] = p->lChild;
}
}
while(top != -1)
{
p = stack[top--];
cout<<p->data<<" ";
}
cout<<endl;
}
int main()
{
TNode *root;
root = createBTree();
reverseLevelVisit(root);
return 0;
}