|
| 1 | +package cn.fyl.first; |
| 2 | + |
| 3 | +public class BinaryTreeNode { |
| 4 | + private Object data; //保存数据 |
| 5 | + private BinaryTreeNode left; //左子树 |
| 6 | + private BinaryTreeNode right; //右子树 |
| 7 | + private BinaryTreeNode root; //根节点 |
| 8 | + |
| 9 | + public BinaryTreeNode getRoot() { |
| 10 | + return root; |
| 11 | + } |
| 12 | + public void setRoot(BinaryTreeNode root) { |
| 13 | + this.root = root; |
| 14 | + } |
| 15 | + public Object getData() { |
| 16 | + return data; |
| 17 | + } |
| 18 | + public void setData(Object data) { |
| 19 | + this.data = data; |
| 20 | + } |
| 21 | + public BinaryTreeNode getLeft() { |
| 22 | + return left; |
| 23 | + } |
| 24 | + public void setLeft(BinaryTreeNode left) { |
| 25 | + this.left = left; |
| 26 | + } |
| 27 | + public BinaryTreeNode getRight() { |
| 28 | + return right; |
| 29 | + } |
| 30 | + public void setRight(BinaryTreeNode right) { |
| 31 | + this.right = right; |
| 32 | + } |
| 33 | + |
| 34 | + //插入功能,插入的值按比父类结点的值大,插入右子树;小,插入左子树 |
| 35 | + public BinaryTreeNode insert(Object o,BinaryTreeNode t){ |
| 36 | + if(t == null){ |
| 37 | + BinaryTreeNode temp = new BinaryTreeNode(); //新建插入值的结点 |
| 38 | + temp.setData(o); |
| 39 | + return temp; |
| 40 | + } |
| 41 | + boolean temp = (int)o > (int)t.getData(); //暂存插入的值跟结点的值比较大小结果 |
| 42 | + if(temp){ //ture时(插入的值大于结点的值大),所以插到右子树 |
| 43 | + System.err.println(temp); |
| 44 | + t.right =insert(o, t.right); |
| 45 | + } |
| 46 | + else{ |
| 47 | + System.out.println(temp); |
| 48 | + t.left = insert(o, t.left); |
| 49 | + } |
| 50 | + return t; |
| 51 | + } |
| 52 | + |
| 53 | + public static void main(String[] args) { |
| 54 | + BinaryTreeNode root = new BinaryTreeNode(); |
| 55 | + BinaryTreeNode left1 = new BinaryTreeNode(); |
| 56 | + BinaryTreeNode right1 = new BinaryTreeNode(); |
| 57 | + BinaryTreeNode left2 = new BinaryTreeNode(); |
| 58 | + BinaryTreeNode left3 = new BinaryTreeNode(); |
| 59 | + root.setData(5); |
| 60 | + root.setLeft(left1); left1.setData(2); |
| 61 | + root.setRight(right1); right1.setData(7); |
| 62 | + left1.setLeft(left2); left2.setData(1); |
| 63 | + right1.setLeft(left3); left3.setData(6); |
| 64 | + BinaryTreeNode temp = root.insert(4, left1); |
| 65 | + System.out.println(left1.getRight().getData()); |
| 66 | + } |
| 67 | + |
| 68 | +} |
0 commit comments