二叉树遍历

二叉树结构

每个节点指向两个子节点,一个左节点,一个右节点,子节点可能为空。
class TreeNode{
		int val;//节点的值
		TreeNode left;//左节点
		TreeNode right;//右节点
		public TreeNode(int val){
			this.val=val;
		}
		public TreeNode() {
			// TODO Auto-generated constructor stub
		}
	}

二叉树构建

通过递归的方式构建一个二叉树
在这里插入图片描述

public TreeNode treeSet(int m) {//num<=14;
		TreeNode node=new TreeNode();
		if(m!=0) {
			node.val=i++;
			node.left=treeSet(m-1);
			node.right=treeSet(m-1);
		}else {
			node=null;
		}
		return node;
	}

二叉树遍历

层序遍历

从根节点开始,一层一层往下遍历。
可使用队列进行实现。
先把根节点放入队列,打印根节点数据,根节点出队列
只要当前节点还有子节点,就依次把左节点和右节点加入队列。
按照进入队列的顺序出队列并且打印数据

在这里插入图片描述

	public void cexu(TreeNode node) {
		LinkedList<TreeNode> list =new LinkedList<>();
		if(node==null) {
			return;
		}
		TreeNode cur=node;
		list.add(cur);
		while(!list.isEmpty()) {
			cur=list.remove();
			System.out.print(cur.val+" ");
			if(cur.left!=null) {
				list.add(cur.left);
			}
			if(cur.right!=null)
				list.add(cur.right);
		}	
	}
1 2 9 3 6 10 13 4 5 7 8 11 12 14 15 

前序遍历

先打印父节点数据,然后遍历左子树,再遍历右子树

public void preorder(TreeNode node) {
			if(node!=null) {
				System.out.print(node.val+" ");
				preorder(node.left);
				preorder(node.right);
			}
		}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

中序遍历

遍历左子树,打印父节点,遍历右子树

public void inorder(TreeNode node) {
		if(node!=null) {
			inorder(node.left);
			System.out.print(node.val+" ");
			inorder(node.right);
		}
	}
4 3 5 2 7 6 8 1 11 10 12 9 14 13 15

后序遍历

遍历左子树,遍历右子树,打印父节点

public void postorder(TreeNode node) {
					if(node!=null) {
						postorder(node.left);
						postorder(node.right);
						System.out.print(node.val+" ");
					}
				}
4 5 3 7 8 6 2 11 12 10 14 15 13 9 1 

前序、中序、后序遍历的代码实现几乎相同,只是输出父节点的次序的位置不同

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值