編寫遞歸算法,從大到小輸出二叉排序樹中所有關鍵字不小於X的數據元素,要求算法的時間復雜度為O(log2(m+n)),其中n為二叉排序樹中所含元素的個數,m為輸出元素個數


從大到小輸出二叉排序樹中不小於x的元素,通過從右子樹到左子樹的遞歸實現

代碼:

 1  // IsBigThanX.cpp : 定義控制台應用程序的入口點。
 2 //  編寫遞歸算法,從大到小輸出給定二叉排序樹中所有關鍵字不小於x的數據元素
 3 
 4 #include "stdafx.h"  
 5 #include<iostream>  
 6 #include<fstream>   
 7 using namespace std;
 8 
 9 typedef int KeyType;
10 struct ElemType { KeyType key; };
11 //定義二叉樹結構體   
12 typedef struct BiTNode
13 {
14     ElemType data;
15     BiTNode  *lchild, *rchild;
16 }*BiTree;
17 BiTree CreateNode(ElemType x)//建立新結點   
18 {
19     BiTree p;
20     p = new BiTNode;
21     p->data = x;
22     p->lchild = p->rchild = NULL;
23     return p;
24 }
25 void InsertBST(BiTree &T, ElemType x)//插入結點   
26 {
27     if (!T) T = CreateNode(x);
28     else if (x.key<T->data.key) InsertBST(T->lchild, x);
29     else if (x.key>T->data.key) InsertBST(T->rchild, x);
30 }
31 void CreateBST(BiTree &T, char fn[])//創建二叉排序樹   
32 {
33     ElemType x; ifstream f;
34     f.open(fn); T = NULL;
35     while (!f.eof()) { f >> x.key; InsertBST(T, x); }
36     f.close();
37 }
38 //visit 函數   
39 void visit(ElemType e)
40 {
41     cout << e.key;
42 }
43 //二叉樹的輸出函數   
44 void preorderlist(BiTree T, void visit(ElemType))
45 {
46     if (T)
47     {
48         visit(T->data);
49         if (T->lchild || T->rchild)
50         {
51             cout << "("; preorderlist(T->lchild, visit);//輸出左孩子   
52             cout << ","; preorderlist(T->rchild, visit);//輸出右孩子   
53             cout << ")";
54         }
55     }
56     else cout << "#";
57 }
58 //從大到小輸出二叉排序樹中不小於x的元素,通過從右子樹到左子樹的遞歸實現   
59 void PrintBSTLx(BiTree &T, KeyType x)
60 {
61     if (!T) return;
62     PrintBSTLx(T->rchild, x);
63     if (T->data.key<x) return;
64     cout << T->data.key << "  ";
65     PrintBSTLx(T->lchild, x);
66 }
67 //主函數   
68 int main()
69 {
70 
71     BiTree T; KeyType x;
72     CreateBST(T, "C:\\Users\\work\\Desktop\\1.txt");
73     cout << "所創建的二叉樹為:";//輸出創建的二叉排序樹   
74     preorderlist(T, visit);
75     cout << endl;
76     cout << "請輸入數值x: ";
77     cin >> x;
78     PrintBSTLx(T, x);
79     cout << endl;
80     system("pause");
81 
82     return 0;
83 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM