本题要求实现一个函数,按照中序遍历的顺序输出给定二叉树中度为1的结点。
函数接口定义:
void InorderPrintNodes( BiTree T);
T是二叉树树根指针,InorderPrintNodes按照中序遍历的顺序输出给定二叉树T中度为1的结点,格式为一个空格跟着一个字符。
其中BiTree结构定义如下:
typedef struct BiTNode
{
ElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
typedef char ElemType;
typedef struct BiTNode
{
ElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
BiTree Create();/* 细节在此不表 */
void InorderPrintNodes( BiTree T);
int main()
{
BiTree T = Create();
printf("Nodes are:");
InorderPrintNodes(T);
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
输入为由字母和'#'组成的字符串,代表二叉树的扩展先序序列。例如对于如下二叉树,输入数据:
ACG#H###BEF###D##
输出样例(对于图中给出的树):
Nodes are: G C E
一开始我的代码是这样子的:
void InorderPrintNodes( BiTree T)
{
if(T==NULL)
return;
InorderPrintNodes(T->lchild);
InorderPrintNodes(T->rchild);
if((T->lchild==NULL&&T->rchild)||(T->lchild&&T->rchild==NULL))
printf(" %c",T->data);
}
测试的时候符合题目的输出,但是不知道为什么会报错,,
但是把 InorderPrintNodes(T->rchild) 的调用放到 if 语句之后就正确了,有人知道是为什么吗QAQ
4月4日更
InorderPrintNodes函数调用方式与 if 语句之间的先后顺序决定着是以何种的方式遍历输出!!
(可恶啊哈哈哈哈做题做着做着才发现不对劲)
现在把几种遍历方式给大家展现出来:
先说说基本定义吧:
先序遍历:先访问根节点,接着递归遍历左子树,最后递归遍历右子树。简记:根 -> 左 -> 右。
中序遍历:先递归遍历左子树,然后访问根节点,最后递归遍历右子树。简记:左 -> 根 -> 右。
后序遍历:先递归遍历左子树,接着递归遍历右子树,最后访问根节点。简记:左 -> 右 -> 根。
各自的实现方式在这里:
#include <iostream>
using namespace std;
// 定义元素类型
typedef char ElemType;
// 定义二叉树节点结构
typedef struct BiTNode {
ElemType data;
struct BiTNode* lchild, * rchild;
} BiTNode, * BiTree;
// 先序遍历
void preOrder(BiTree root) {
if (root != nullptr) {
cout << root->data;
preOrder(root->lchild);
preOrder(root->rchild);
}
}
// 中序遍历
void inOrder(BiTree root) {
if (root != nullptr) {
inOrder(root->lchild);
cout << root->data;
inOrder(root->rchild);
}
}
// 后序遍历
void postOrder(BiTree root) {
if (root != nullptr) {
postOrder(root->lchild);
postOrder(root->rchild);
cout << root->data;
}
}
// 创建二叉树
BiTree createBiTree() {
char x;
cin >> x;
if (x == '#') {
return nullptr;
}
BiTree node = new BiTNode;
node->data = x;
node->lchild = createBiTree();
node->rchild = createBiTree();
return node;
}
int main() {
BiTree root = createBiTree();
if (root) {
preOrder(root);
cout << endl;
inOrder(root);
cout << endl;
postOrder(root);
cout << endl;
}
}
最终代码如下:
void InorderPrintNodes( BiTree T)
{
if(T==NULL)
return;
InorderPrintNodes(T->lchild);
if((T->lchild==NULL&&T->rchild)||(T->lchild&&T->rchild==NULL))
printf(" %c",T->data);
InorderPrintNodes(T->rchild);
}