二叉树的相关算法

树的遍历

二叉树按层遍历

 1 public class BinaryTree {
 2 
 3     private int data;
 4 
 5     private BinaryTree left;
 6 
 7     private BinaryTree right;
 8 
 9     public BinaryTree() {
10     }
11 
12     public BinaryTree(int data, BinaryTree left, BinaryTree right) {
13         this.data = data;
14         this.left = left;
15         this.right = right;
16     }
17 
18     @Override
19     public String toString() {
20         return "BinaryTree{" +
21                 "data=" + data +
22                 ", left=" + left +
23                 ", right=" + right +
24                 '}';
25     }
26 
27     public int getData() {
28         return data;
29     }
30 
31     public void setData(int data) {
32         this.data = data;
33     }
34 
35     public BinaryTree getLeft() {
36         return left;
37     }
38 
39     public void setLeft(BinaryTree left) {
40         this.left = left;
41     }
42 
43     public BinaryTree getRight() {
44         return right;
45     }
46 
47     public void setRight(BinaryTree right) {
48         this.right = right;
49     }
50 
51     public BinaryTree buildBinaryTree() {
52         BinaryTree root = new BinaryTree(1, null, null);
53         BinaryTree t1 = new BinaryTree(2, null, null);
54         BinaryTree t2 = new BinaryTree(3, null, null);
55         BinaryTree t3 = new BinaryTree(4, null, null);
56         BinaryTree t4 = new BinaryTree(5, null, null);
57         BinaryTree t5 = new BinaryTree(6, null, null);
58         root.setLeft(t1);
59         root.setRight(t2);
60         t1.setLeft(t3);
61         t1.setRight(t4);
62         t3.setLeft(t5);
63         return root;
64     }
65 
66     public void levelIterator(BinaryTree root) {
67         
68         LinkedList<BinaryTree> queue = new LinkedList<>();
69         //将树添加到队列中
70         queue.offer(root);
71 
72         while (!queue.isEmpty()) {
73             BinaryTree current = queue.poll();
74             System.out.println(current.data);
75             if (current.left != null) {
76                 queue.offer(current.left);
77             }
78 
79             if (current.right != null) {
80                 queue.offer(current.right);
81             }
82         }
83     }
84 
85     public static void main(String[] args) {
86         BinaryTree binaryTree = new BinaryTree();
87         BinaryTree root = binaryTree.buildBinaryTree();
88         binaryTree.levelIterator(root);
89     }
90 }

 

posted @ 2020-04-20 12:14  seedss  阅读(170)  评论(0编辑  收藏  举报