You are supposed to output, in decreasing order, all the elements no less than X in a binary search tree T.
Format of function:
void Print_NLT( Tree T, int X );
where Tree is defined as the following:
typedef struct TreeNode *Tree;
struct TreeNode {
int Element;
Tree Left;
Tree Right;
};
The function is supposed to use Output(X) to print X.
Sample program of judge:
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode *Tree;
struct TreeNode {
int Element;
Tree Left;
Tree Right;
};
Tree BuildTree(); /* details omitted */
void Output( int X ); /* details omitted */
void Print_NLT( Tree T, int X );
int main()
{
Tree T;
int X;
T = BuildTree();
scanf("%d", &X);
Print_NLT( T, X );
printf("End\n");
return 0;
}
/* Your function will be put here */
Sample Output 1(for the tree shown in Figure 1):
92 91 90 85 81 80 End
Sample Output 2:
End
Analysis:
先向右找最大的数,然后判断该数是否大于X,大于或等于就输出,小于就直接退出函数。
Code:
//按递减顺序输出比X大的数(包括等于X的数)
void Print_NLT( Tree T, int X )
{
if(T == NULL)
return;
Print_NLT(T->Right,X);//先找右子树,一直到右子树的最后一个结点才开始进入if,然后开始调用递归
if(T->Element>=X){
printf("%d ",T->Element);
}
Print_NLT(T->Left,X);//找左子树
}