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() +" "); } }推荐最近看的一本书:
