我是靠谱客的博主 悦耳小蝴蝶,这篇文章主要介绍2016/11/10 1002. 二叉查找树的遍历,现在分享给大家,希望可以做个参考。

先按输入构建出二叉树,然后遍历即可。二叉查找树的建立不难,对每一个输入,从根节点出发,小的往左,大的往右,若空则插入即可。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <iostream> using namespace std; class Node { public: Node(int a = 0) { v = a; left = nullptr; right = nullptr; } Node *left; Node *right; int v; }; class Tree { public: Tree(int a=0) { root = new Node(a); } void insert(int a) { Node* p = root; for (;;) { if (a > p->v) { if (p->right == nullptr) { p->right = new Node(a); break; } else { p = p->right; continue; } } if (a < p->v) { if (p->left == nullptr) { p->left = new Node(a); break; } else { p = p->left; continue; } } } } Node *root; }; void inorder(Node *root) { if (root == nullptr) { return; } inorder(root->left); cout << root->v << " "; inorder(root->right); } void preorder(Node *root) { if (root == nullptr) { return; } cout << root->v << " "; preorder(root->left); preorder(root->right); } int main() { int t; for (;;) { cin >> t; if (t == 0)break; int temp; cin >> temp; Tree T(temp); for (int i = 2; i <= t; i++) { int a; cin >> a; T.insert(a); } inorder(T.root); cout << endl; preorder(T.root); cout << endl; } }


最后

以上就是悦耳小蝴蝶最近收集整理的关于2016/11/10 1002. 二叉查找树的遍历的全部内容,更多相关2016/11/10内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(46)

评论列表共有 0 条评论

立即
投稿
返回
顶部