您的位置:首页 > 其它

从大到小打印BST结点

2016-01-06 09:10 197 查看
问题描述:Write a function that prints out the node values for a BST in sorted order from highest to lowst.

问题分析:BST是一种特殊的二叉树,对于每一个结点,其左子树所有结点的值都小与该结点值,右子树所有结点的值都大于该结点值。所以利用in-order遍历能很好地打印出排好序的结点。不过需要注意的是,平常使用的in-order是LNR,而在此程序中应该把in-order打印的顺序改变为RNL.

代码实现:

#include <iostream>
using namespace std;

// BST的结点
typedef struct node
{
int key;
struct node *lChild, *rChild;
}Node, *BST;

// 在给定的BST中插入结点,其数据域为element, 使之称为新的BST
bool BSTInsert(Node * &p, int element)
{
if(NULL == p) // 空树
{
p = new Node;
p->key = element;
p->lChild = p->rChild = NULL;
return true;
}

if(element == p->key) // BST中不能有相等的值
return false;

if(element < p->key)  // 递归
return BSTInsert(p->lChild, element);

return BSTInsert(p->rChild, element); // 递归
}

// 建立BST
void createBST(Node * &T, int a[], int n)
{
T = NULL;
int i;
for(i = 0; i < n; i++)
{
BSTInsert(T, a[i]);
}
}

// 中序遍历
void inOrderTraverse(BST T)
{
if(T)
{
inOrderTraverse(T->rChild);
cout << T->key << " ";
inOrderTraverse(T->lChild);
}
}

int main()
{
int a[10]={2,3,1,5,8,9,0,4,6,7};
int n = 10;
BST T;

// 并非所有的a[]都能构造出BST,所以,最好对createBST的返回值进行判断
createBST(T, a, n);
//打印出中序遍历
inOrderTraverse(T);
cout << endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: