开局一张糊糊的图
- 节点
public class TreeNode {
public int val;//节点值
public TreeNode left;//指向该节点的左孩子 null表示无左孩子 进一步视为左子树
public TreeNode right;//指向该节点的右孩子
public TreeNode(int val) {
this.val = val;
}
@Override
public String toString() {
return String.format("TreeNode{%c}",val);
}
}
- 生成二叉树
public class BuildTree {
public static TreeNode buildTree(){
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');
a.left=b;a.right=c;
b.left=d;b.right=e;
c.left=f;c.right=g;
e.right=h;
return a;//返回根节点
}
}
- 前序、中序、后序遍历(用递归实现)
public class TreeTraversal {
public static void main(String[] args) {
TreeNode root=BuildTree.buildTree();
System.out.print("前序遍历:");
preorder(root);
System.out.println();
System.out.print("中序遍历:");
inorder(root);
System.out.println();
System.out.print("后序遍历:");
postorder(root);
System.out.println();
}
public static void preorder(TreeNode root) {//前序遍历
if (root == null){
return;
}
//遍历任意节点 只需打印根的值
System.out.printf("%c ",root.val);
//递归
preorder(root.left);//root.left代表一整棵左子树
preorder(root.right);
}
public static void inorder(TreeNode root){//中序遍历
if (root==null){
return;
}
inorder(root.left);
System.out.printf("%c ",root.val);
inorder(root.right);
}
public static void postorder(TreeNode root){
if (root==null){
return;
}
postorder(root.left);
postorder(root.right);
System.out.printf("%c ",root.val);
}
}
- 执行结果