算法:二叉树的遍历

1、什么是二叉树?

     二叉树是n(n>=0)个结点的有限集合,该集合或者为空集(称为空二叉树),或者由一个根结点和两棵互不相交的、分别称为根结点的左子树和右子树组成。二叉树是一种非常重要的数据结构,非常多的数据结构都是基于二叉树的基础演变而来的。

2、二叉树的遍历主要有以下三种方式:

1)先序序遍历(根-->左-->右)

  • 访问根节点 

  • 先序遍历左子树 

  • 先序遍历右子树       

2)中序遍历(左-->根-->右)

  • 中序遍历左子树 

  • 访问根节点 

  • 中序遍历右子树       

3)后序遍历(左-->右-->根)

  • 后序遍历左子树

  • 后序遍历右子树

  • 访问根节点 

3、二叉树遍历的代码实现

public class OrderNode {	
    public static void main(String[] args) {	
        Node node = new Node();	
        preOrderRecur(node);	

	
    }	

	
    //二叉树的先序遍历 采用递归的方式	
    private static void  preOrderRecur(Node head){	
        if(head == null){	
            return;	
        }	
        System.out.println(head.getValue() + "");	
        preOrderRecur(head.left);	
        preOrderRecur(head.right);	
    }	

	
    //二叉树的中序遍历 采用递归方式	
    private static  void inOrderRecur(Node head){	
        if(head == null){	
            return;	
        }	
        inOrderRecur(head.left);	
        System.out.println(head.getValue() +" ");	
        inOrderRecur(head.right);	
    }	

	

	
    //二叉树的后序遍历,采用递归的方式	
    private static void posOrderRecur(Node head){	
        if(head == null){	
            return;	
        }	
        posOrderRecur(head.left);	
        posOrderRecur(head.right);	
        System.out.println(head.getValue() +" ");	
    }	
}	

推荐最近看的一本书:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值