本文主要是介绍【王道数据结构】【chapter7查找】【P309t9】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
设计一个算法,从大到小输出二叉排序树中所有值不小于k的关键字
#include <iostream>
#include <queue>
typedef struct node{int data;struct node* left;struct node* right;
}node,*pnode;pnode buynode(int x)
{pnode tmp=(pnode) malloc(sizeof (node));tmp->data=x;tmp->left= nullptr,tmp->right= nullptr;return tmp;
}void build_tree(pnode &root,int data)
{if(root== nullptr) {root= buynode(data);return;}if(data<root->data)build_tree(root->left,data);if(data==root->data) return;if(data>root->data) build_tree(root->right,data);
}void print(pnode root)
{if(root== nullptr) return;std::queue<pnode> record;record.push(root);int size=record.size();while(!record.empty()){pnode head=record.front();printf("%3d",head->data);record.pop();if(head->left) record.push(head->left);if(head->right) record.push(head->right);if(--size==0) puts(""),size=record.size();}
}void output(pnode root,int k)
{if(root== nullptr) return;output(root->right,k);if(root->data>=k) printf("%3d",root->data);output(root->left,k);
}
int main() {pnode r1= nullptr;//p295图7.8(a),这是一棵平衡二叉排序树int a[]={45,24,12,37,28,40,55,53,60,70};for(int i=0;i<10;i++){build_tree(r1,a[i]);}print(r1);printf("the order is:");output(r1,27);//从大到小打印所有大于等于27的序列puts("");pnode r2= nullptr;//p295图7.8(b),这是一棵非平衡二叉树int b[]={12,24,28,37,40,45,53,55,60,70};for(int i=0;i<10;i++){build_tree(r2,b[i]);}print(r2);printf("the order is:");output(r2,27);//从大到小打印所有大于等于27的序列puts("");return 0;
}
这篇关于【王道数据结构】【chapter7查找】【P309t9】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!