从大到小打印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.
代码实现:
问题分析: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; }
相关文章推荐
- 【摘】top命令
- SQL中distinct的用法
- 模糊查询
- 安装cocoapods时出现错误 Operation not permitted - /usr/bin/pod
- 免费的就是最贵的
- http协议详解<一>
- php 抓取页面数据
- shell\comdlg32\fileopensave.cpp(9456)\COMDLG32.dll!
- 获取Android设备唯一标识码
- https访问glassfish替换glassfish证书
- 介绍几种c/c++编译方式(记事本编译、vim编译)
- 关于年终奖励的扣税算法BUG
- 黑色帽子(南阳oj455)(逻辑思维题)
- android中listview分页加载数据
- ionic学习笔记5
- 中新创科网络远程电源集中控制管理系统解决方案
- ArcEngine由点生成TIN
- PHP常用的正则表达式
- android点击事件
- protobuf 实战(2)mac 生成篇