class TreeNode{
int value;
TreeNode leftNode;
TreeNode rightNode;
//构造函数
TreeNode(int v){
this.value = v;
}
}
public static void main(String[] args){
TreeNode node1 = new TreeNode(10);
TreeNode node2 = new TreeNode(3);
TreeNode node3 = new TreeNode(30);
TreeNode node4 = new TreeNode(15);
TreeNode node5 = new TreeNode(6);
node1.leftNode = node2;
node1.rightNode = node3;
node3.leftNode = node4;
node2.rightNode = node5;
//结构:10 - 30 - 15
// - 3 - 6
一般遍历有深度优先和广度优先两种,深度包括先序、后序、中序遍历。这三者区别主要是先序遍历优先访问中间节点,中序是在中间访问中间节点(先访问左节点,后中节点,后右节点),后序遍历是先左右节点最后中间节点。
static void traversal(TreeNode node){
//先序遍历
if(node == null) return;
System.out.println(node.value);
traversal(node.leftNode);
traversal(node.rightNode);
}
static void layerTraversal(TreeNode node){
//层次遍历(bfs)
if(node == null) return;
LinkedList<TreeNode> list = new LinkedList<TreeNode>();
list.add(node);
while(!list.isEmpty()){
TreeNode node_now = list.removeFirst();
System.out.println(node_now.value);
// 左右儿子通通入队
if(node_now.leftNode != null)
list.add(node_now.leftNode);
if(node_now.rightNode != null)
list.add(node_now.rightNode);
}
}