二叉树的遍历方式有先序遍历,中序遍历,后序遍历。
先序遍历:先访问根节点,后访问左孩子,之后访问右孩子
中序遍历:先访问左孩子,之后访问根节点,之后访问右孩子
后序遍历:先访问左孩子,后访问右孩子,之后访问根节点
先序遍历算法思想:
1.声明一个list数组
2.声明一个节点的数据结构node
3.从二叉树的根节点 开始,先将二叉树的根节点存入数组
4.访问该节点是否有左孩子,若没有那么记录该节点
5.访问该节点有没有右孩子,若没有那么存入数组
先序/中序/后序算法实现:
import com.sun.javafx.binding.StringFormatter; import java.util.ArrayList; import java.util.List; //使用节点来保存数据 //节点的左右子树,分别存储结点的左右孩子 //定义节点结构 class node{ //存储数据的位置 private String data; // private node leftChild; //指针指向右子树 public node rightChild; public node(String data,node leftChild,node rightChild){ this.data = data; this.leftChild = leftChild; this.rightChild = rightChild; } public String getData(){ return this.data; } public node getLeftChild(){ return this.leftChild; } public node getRightChild(){ return this.rightChild; } } public class tree { //定义根节点 private node root; List<String> strings = new ArrayList<>(); //初始化数据 public void init(){ node node5 = new node("5",null,null); node node4 = new node("4",null,null); node node3 = new node("3",null,null); node node2 = new node("2",node4,node5); node node1 = new node("1",node2,node3); root = node1; } public tree(){ init(); } //先序遍历,遍历的时候先把数的根节点存入list数组中 //之后判断左子树是否存在,若存在,就递归调用该方法 public void preSerch(node node){ //判断是否为空 if(node == null){ return; } //不为空就把根节点对应的数据存入数组中 strings.add(node.getData()); //判断左节点是否为空 if(node.getLeftChild()!=null){ //递归 preSerch(node.getLeftChild()); } if(node.getRightChild()!=null){ //递归 preSerch(node.getRightChild()); } } public void preSerch(){ //判断根节点是否为空 if(root == null){ return; } //不为空就把根节点对应的数据存入数组中 strings.add(root.getData()); //判断左节点是否为空 if(root.getLeftChild()!=null){ //递归 preSerch(root.getLeftChild()); } if(root.getRightChild()!=null){ //递归 preSerch(root.getRightChild()); } //输出结果 strings.stream().forEach(e->{ System.out.println(e); }); } //中序遍历 //判断当前结点是否有左孩子,若有左孩子 那么递归 public void leftSerch(node node){ //判断根节点是否为null if(node == null){ return; } //判断是否有左节点 if(node.getLeftChild()!=null){ //递归继续判断是否有左节点 leftSerch(node.getLeftChild()); } //若是没有左节点,那么就将当前结点存入数组 strings.add(node.getData()); //判断是否有右孩子 if(node.getRightChild()!=null){ //继续递归看是否有左孩子 leftSerch(node.getRightChild()); } } public void leftSerch(){ if(root == null){ return; } if(root.getLeftChild()!=null){ //继续访问左节点 leftSerch(root.getLeftChild()); } strings.add(root.getData()); if (root.getRightChild()!=null){ //继续访问左节点 leftSerch(root.getRightChild()); } //输出结果 strings.stream().forEach(e->{ System.out.println(e); }); } //获取二叉树的深度,也是通过递归的方法来获取 public int getHeight(node node){ if(node == null){ return 0; } //若没有左右孩子,那么深度是1; if(node.getRightChild() == null&&node.getLeftChild() == null){ return 1; } int left = 0;int right = 0; if(node.getLeftChild()!=null){ left = getHeight(node.getLeftChild()); } if(node.getRightChild()!=null){ right = getHeight(node.getRightChild()); } return left>right?left+1:right+1; } public static void main(String a[]){ tree tree = new tree(); tree.leftSerch(); tree.getHeight(tree.root); } }