-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTree.java
65 lines (62 loc) · 1.51 KB
/
BinaryTree.java
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
package com.day4;
import jdk.nashorn.internal.ir.IfNode;
/**
* @author Jackson
* @date 2019-10-28 16:04
*/
public class BinaryTree {
// 根节点
private Node root;
// 增加节点
public void add(int data){
if (root == null){
root = new Node(data);
}else {
root.addNode(data);
}
}
// 打印节点
public void print(){
if (root != null){
root.printNode();
}
}
private class Node{
// 数据域
private int data;
// 左子树
private Node left;
// 右子树
private Node right;
// 构造方法
public Node(int data){
this.data = data;
}
// 增加节点
public void addNode(int data){
if (data < this.data){
if (this.left == null){
this.left = new Node(data);
}else {
this.left.addNode(data);
}
}else {
if (this.right == null){
this.right = new Node(data);
}else {
this.right.addNode(data);
}
}
}
// 遍历(中序遍历)
public void printNode(){
if (this.left != null){
this.left.printNode();
}
System.out.print(this.data + "=>");
if (this.right != null){
this.right.printNode();
}
}
}
}