一道二叉查找树的应用题

题目:

建立一颗二叉查找树,输出每个节点的数值以及该节点的左右子树的数值。

格式如下:

输入格式:

第一行输入一个正整数 N (1 <= N <= 1000),代表序列里元素个数。

第二行输入 N 个正整数,代表序列 a 的 N 个元素(0 <= ai <= 10000)。保证序列里的元素值互不相同。

输出格式:

请按格式“a(b, c)”,输出引号之间的内容,a 代表每个结点的权值,b 代表其左孩子结点权值,c 代表右孩子结点权值,如果孩子结点为空,则输出“#”代替。一个结点输出一行,按结点的权值从小到大输出。注意输出“,”后面的空格。

答案:

二叉查找树的中序遍历是从小到大排列的,所以只用改变中序遍历代码即可

 1 #include<iostream>
 2 using namespace std;
 3 class Node {
 4 public:
 5     int data;
 6     Node *lchild, *rchild, *father;
 7     Node(int _data, Node *_father = NULL) {
 8         data = _data;
 9         lchild = NULL;
10         rchild = NULL;
11         father = _father;
12     }
13     ~Node() {
14         if (lchild != NULL) {
15             delete lchild;
16         }
17         if (rchild != NULL) {
18             delete rchild;
19         }
20     }
21     void insert(int value) {               //二叉查找树的插入(递归)
22         if (value == data) {
23             return;
24         } else if (value > data) {
25             if (rchild == NULL) {
26                 rchild = new Node(value, this);
27             } else {
28                 rchild->insert(value);
29             }
30         } else {
31             if (lchild == NULL) {
32                 lchild = new Node(value, this);
33             } else {
34                 lchild->insert(value);
35             }
36         }
37     }
38     void inorder() {
39          if (lchild != NULL) {
40              lchild->inorder();
41          }
42          cout << data<<"(";
43         if(this->lchild==NULL){
44             cout<<"#";
45         }
46         else{
47             cout<<this->lchild->data;
48         }
49          cout<<","<<" ";
50         if(this->rchild==NULL){
51             cout<<"#";
52         }
53         else{
54             cout<<this->rchild->data;
55         }
56         cout<<")"<<endl;
57          if (rchild != NULL) {
58              rchild->inorder();
59          }
60      }
61 };
62 class BinaryTree {
63 private:
64     Node *root;
65 public:
66     BinaryTree() {
67         root = NULL;
68     }
69     ~BinaryTree() {
70         if (root != NULL) {
71             delete root;
72         }
73     }
74     void insert(int value) {
75         if (root == NULL) {
76             root = new Node(value);
77         } else {
78             root->insert(value);
79         }
80     }
81     void inorder() {                           //中序
82          root->inorder();
83     }
84 };
85 int main() {
86     BinaryTree binarytree;
87     int n;
88     cin>>n;
89     int arr[n];
90     for (int i = 0; i < n; i++) {
91         cin>>arr[i];
92         binarytree.insert(arr[i]);
93     }
94     binarytree.inorder();
95     return 0;
96 }
原文地址:https://www.cnblogs.com/Reindeer/p/5691776.html