java写二叉树算法,实现添加数据形成二叉树功能,并打印出来

本文介绍了一个简单的二叉树类的实现,包括插入、查找等基本操作,并提供了中序和前序遍历的方法来展示树的结构。通过具体的示例代码展示了如何构建一棵二叉树并进行遍历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

来源:网络 作者:未知
public class MyTest {
private myTree tree;

/**
*二叉树的插入,参数为(关键字,数据)
*
**/
public void insert(int key, int d
1.public class MyTest {
2. private myTree tree;
3.
4. /**
5. *二叉树的插入,参数为(关键字,数据)
6. *
7. **/
8. public void insert(int key, int data) {
9. if (tree == null) {
10. tree = new myTree();
11. tree.key = key;
12. tree.data = data;
13. } else {
14. myTree newTree = new myTree();
15. newTree.key = key;
16. newTree.data = data;
17. myTree parent = tree;
18. while (true) {
19. if (newTree.key < parent.key) {
20. if (parent.leftChild == null) {
21. parent.leftChild = newTree;
22. return;
23. } else {
24. parent = parent.leftChild;
25. }
26. } else if (newTree.key > parent.key) {
27. if (parent.rightChild == null){ parent.rightChild = newTree;
28. return;
29. } else {
30. parent = parent.rightChild;
31. }
32. }
33. }
34.
35. }
36. }
37.
38. /**
39. * 二叉树的查找,参数为(关键字),返回值为 myTree的一个实例
40. *
41. * **/
42. public myTree find(int key) {
43. if (tree == null)
44. return null;
45. myTree curr = new myTree();
46. curr.key = key;
47. myTree parent = tree;
48. while (true) {
49. if (parent == null) {
50. return null;
51. } else if (curr.key == parent.key) {
52. return parent;
53. } else if (curr.key > parent.key) {
54. parent = parent.rightChild;
55. } else if (curr.key < parent.key) {
56. parent = parent.leftChild;
57. }
58. }
59. }
60.
61. /*
62. *
63. * 递归的二叉树中序遍历
64. *
65. *
66. */
67. private static void midOrder(myTree tree) {
68. if (tree != null) {
69. midOrder(tree.leftChild);
70. System.out.println(tree + "," + tree.key + "," + tree.data);
71. midOrder(tree.rightChild);
72. }
73. }
74.
75. /*
76. * 前序遍历
77. */
78. private static void frontOrder(myTree tree) {
79. if (tree != null) {
80. System.out.println("" + tree.key + " , " + tree.data);
81. frontOrder(tree.leftChild);
82. frontOrder(tree.rightChild);
83. }
84. }
85.
86. public static void main(String[] args) {
87. System.out.println("Tree view Begin");
88. MyTest t1 = new MyTest();
89. t1.insert(8, 25);
90. t1.insert(5, 9);
91. t1.insert(58, 87);
92. t1.insert(13, 82);
93. t1.insert(4, 8);
94. t1.insert(12, 54);
95. t1.insert(53, 123);
96. t1.insert(56, 47);
97. t1.insert(2, 75);
98. t1.insert(34, 5);
99. t1.insert(6, 23);
100. System.out.println("现在开始遍历:");
101. frontOrder(t1.tree);
102. midOrder(t1.tree);
103. }
104.
105.}
106.
107.class myTree {
108. int key;
109. int data;
110. myTree leftChild;
111. myTree rightChild;
112.}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值