1.先定义节点
java
/*
定义一个树节点
*/
public class TreeNode {
int val; //存储值
TreeNode left; //左子树
TreeNode right; //右子树
//无参构造方法
TreeNode (){
}
//有参构造方法
TreeNode(int val){
this.val=val;
}
TreeNode(int val,TreeNode left,TreeNode right){
this.val=val;
this.left=left;
this.right=right;
}
}
2.手动创建一个二叉树并遍历。
此处同时使用了前序遍历、中序遍历、后序遍历,实际只使用一种方法即可。
java
public class BinaryTreeDemo {
public static void main(String[] args) {
//手动创建一个树
TreeNode root=createTree();
//1.前序遍历
List<Integer> result=preorderTraversal(root);
//2.中序遍历
List<Integer> result2=inorderTraversal(root);
//3.后序遍历
List<Integer> result3=postorderTraversal(root);
System.out.println(result);
System.out.println(result2);
System.out.println(result3);
}
//手动创建二叉树
public static TreeNode createTree(){
TreeNode root=new TreeNode(1); //创建根节点
TreeNode treeNode2=new TreeNode(2);
TreeNode treeNode3=new TreeNode(3);
TreeNode treeNode4=new TreeNode(4);
TreeNode treeNode5=new TreeNode(5);
TreeNode treeNode6=new TreeNode(6);
TreeNode treeNode7=new TreeNode(7);
root.left = treeNode2;
root.right = treeNode3;
treeNode2.left = treeNode4;
treeNode2.right = treeNode5;
treeNode3.left = treeNode6;
treeNode3.right = treeNode7;
return root;
}
//前序遍历
public static List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result=new ArrayList<>();
preorder(root,result);
return result;
}
public static void preorder(TreeNode root,List<Integer> result){
if(root==null) return; //如果当前节点为空,结束递归
result.add(root.val); //不为空,则将当前节点的值,加入链表中
preorder(root.left,result);
preorder(root.right,result);
}
//中序遍历
public static List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result=new ArrayList<>();
inorder(root,result);
return result;
}
public static void inorder(TreeNode root,List<Integer> result){
if(root==null) return;
inorder(root.left,result);
result.add(root.val);
inorder(root.right,result);
}
//后序遍历
public static List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result=new ArrayList<>();
postorder(root,result);
return result;
}
public static void postorder(TreeNode root,List<Integer> result){
if(root==null) return;
postorder(root.left,result);
postorder(root.right,result);
result.add(root.val);
}
}