首页 > 代码库 > 树-层次遍历
树-层次遍历
package com.charles.algorithm;
import java.util.LinkedList;
import java.util.Queue;
public class Tree {
private Queue<TreeNode> elements = new LinkedList<TreeNode>();
public static void main(String[] args) {
/*
* @desc: construct a tree:
* root
* A B
* C D E F
* G H I J
*/
TreeNode root = new TreeNode("root");
TreeNode A = new TreeNode("A");
TreeNode B = new TreeNode("B");
TreeNode C = new TreeNode("C");
TreeNode D = new TreeNode("D");
TreeNode E = new TreeNode("E");
TreeNode F = new TreeNode("F");
TreeNode G = new TreeNode("G");
TreeNode H = new TreeNode("H");
TreeNode I = new TreeNode("I");
TreeNode J = new TreeNode("J");
root.setLeft(A);
root.setRight(B);
A.setLeft(C);
A.setRight(D);
B.setLeft(E);
B.setRight(F);
C.setLeft(G);
C.setRight(H);
D.setLeft(I);
D.setRight(J);
Tree tree = new Tree();
tree.broadTraval(root);
}
public void broadTraval(TreeNode root) {
if (null != root) {
elements.add(root);
} else {
return;
}
while (0 < elements.size()) {
root = elements.poll();
System.out.println(root.getData());
if (null != root.getLeft()) {
elements.add(root.getLeft());
}
if (null != root.getRight()) {
elements.add(root.getRight());
}
}
}
}
class TreeNode {
/*
* @Desc: define a tree node
*/
private String data;
private TreeNode left;
private TreeNode right;
public TreeNode() {
}
public TreeNode(String data) {
super();
this.data = http://www.mamicode.com/data;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = http://www.mamicode.com/data;
}
public TreeNode getLeft() {
return left;
}
public void setLeft(TreeNode left) {
this.left = left;
}
public TreeNode getRight() {
return right;
}
public void setRight(TreeNode right) {
this.right = right;
}
}
树-层次遍历