1.Java 中没有 Tree 的数据结构,不过我们可以自己写一个:
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
2.初始化遍历的树
.
TreeNode t4=new TreeNode(4,null,null);
TreeNode t8=new TreeNode(8,null,null);
TreeNode t6=new TreeNode(6,t4,t8);
TreeNode t12=new TreeNode(12,null,null);
TreeNode t16=new TreeNode(16,null,null);
TreeNode t14=new TreeNode(14,t12,t16);
TreeNode t10=new TreeNode(10,t6,t14);
3.前序遍历
public static void preOrder(TreeNode treeNode){
System.out.println(treeNode.val);
if(treeNode.left!=null){
preOrder(treeNode.left);
}
if(treeNode.right!=null){
preOrder(treeNode.right);
}
}
4.中序遍历(值从小到大遍历)
public static void inOrder(TreeNode treeNode){
if(treeNode.left!=null){
inOrder(treeNode.left);
}
System.out.println(treeNode.val);
if(treeNode.right!=null){
inOrder(treeNode.right);
}
}
5.后序遍历
public static void postOrder(TreeNode treeNode){
if(treeNode.left!=null){
postOrder(treeNode.left);
}
if(treeNode.right!=null){
postOrder(treeNode.right);
}
System.out.println(treeNode.val);
}
来源:CSDN
作者:风起尘落
链接:https://blog.csdn.net/qq_34707456/article/details/103927827