其他分享
首页 > 其他分享> > 二叉树的学习:前中后序遍历方法

二叉树的学习:前中后序遍历方法

作者:互联网

二叉树的前中后序遍历:

前序遍历:根,左子树,右子树;

中序遍历:左子树,根,右子树;

后序遍历:左子树,右子树,根;

例如上图遍历结果:

前序遍历:ABDEHCFG;

中序遍历:DBEHAFCG;

后序遍历:DHEBFGCA;

首先建立树节点类,构造节点类的属性;

public class TreeNode{
   public int val;
   public TreeNode left;//指向该节点的左孩子
                        //left==null 没有左孩子
   public TreeNode right;

   public TreeNode (int val){
     this.val=val;
}
@Override
    public String toString() {
        return String.format("TreeNode{%c}", val);
    }
}

构建一个树的类:

pubic class BuildTree{
  public static TreeNode buildTree1(){
        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 static void main(String[] args) {
        buildTree1();
    }
}

接下来是构建前中后序遍历,都用的递归:

前序遍历 preorder   中序遍历 inorder   后序遍历 postorder

主要是按照前面介绍的遍历顺序进行遍历;

前序遍历:

public static void preorder(TreeNode root){
     if(root==null){
        return null;//当根节点不存在的时候是空树,直接返回空;
}
    
         System.out.printf("%c ", root.val);

        preorder(root.left);  // root.left 代表是一整棵左子树
                             //这一步一直到空才会执行下一步;是方法内部调用该方法,递归的核心意义
        preorder(root.right);
       

}

下面是中序遍历和后序遍历:方法的原理都是一样的;

public static TreeNode inorder(TreeNode root){
        if (root==null){
            return null;
        }
        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);
    }

 

标签:遍历,TreeNode,前中,right,二叉树,root,public,left
来源: https://blog.csdn.net/weixin_47753602/article/details/115255445