Skip to content

Commit c53e09d

Browse files
committed
二叉树实现MyBinaryTree
1 parent 3b471a5 commit c53e09d

File tree

2 files changed

+54
-5
lines changed

2 files changed

+54
-5
lines changed

group07/562247675/homework/homework-0226/src/main/java/com/coding2017/group7/homework/c0226/MyBinaryTreeNode.java

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,15 @@
22

33
public class MyBinaryTreeNode {
44

5-
private Object data;
5+
private Comparable data;
66
private MyBinaryTreeNode left;
77
private MyBinaryTreeNode right;
88

9-
public Object getData() {
9+
public Comparable getData() {
1010
return data;
1111
}
1212

13-
public void setData(Object data) {
13+
public void setData(Comparable data) {
1414
this.data = data;
1515
}
1616

@@ -30,8 +30,23 @@ public void setRight(MyBinaryTreeNode right) {
3030
this.right = right;
3131
}
3232

33-
public MyBinaryTreeNode insert(Object o) {
34-
return null;
33+
public MyBinaryTreeNode insert(Comparable o) {
34+
if (data == null) {
35+
data = o;
36+
}
37+
int compare = o.compareTo(data);
38+
if (compare < 0) {
39+
if (left == null) {
40+
left = new MyBinaryTreeNode();
41+
}
42+
left.insert(o);
43+
} else if (compare > 0) {
44+
if (right == null) {
45+
right = new MyBinaryTreeNode();
46+
}
47+
right.insert(o);
48+
}
49+
return this;
3550
}
3651

3752
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.coding2017.group7.homework.c0226;
2+
3+
import org.junit.Assert;
4+
import org.junit.Test;
5+
6+
public class MyBinaryTreeNodeTest {
7+
8+
9+
@Test
10+
public void insert() throws Exception {
11+
MyBinaryTreeNode node = new MyBinaryTreeNode();
12+
node.insert(5)
13+
.insert(2)
14+
.insert(7)
15+
.insert(1)
16+
.insert(6)
17+
.insert(4)
18+
.insert(8)
19+
.insert(3);
20+
Comparable data1 = node.getLeft().getLeft().getData();
21+
Comparable data4 = node.getLeft().getRight().getData();
22+
Comparable data6 = node.getRight().getLeft().getData();
23+
Comparable data8 = node.getRight().getRight().getData();
24+
Comparable data3 = node.getLeft().getRight().getLeft().getData();
25+
Assert.assertEquals(1, data1);
26+
Assert.assertEquals(4, data4);
27+
Assert.assertEquals(6, data6);
28+
Assert.assertEquals(8, data8);
29+
Assert.assertEquals(3, data3);
30+
31+
}
32+
33+
34+
}

0 commit comments

Comments
 (0)