二叉树的宽度(广度)优先遍历

本文介绍了一种使用队列实现的二叉树宽度优先遍历算法,并提供了详细的Java代码示例。通过该算法,可以按层次顺序访问二叉树的所有节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二叉树的宽度(广度)优先遍历

Java代码如下:

import java.util.LinkedList;
import java.util.Queue;
public class Test1 {
	private static class BTNode{
		public int Data;
		public BTNode Left;
		public BTNode Right;
		public BTNode(int data) {
			Data=data;
			Left=null;
			Right=null;
		}
		public static BTNode CreateBinaryTree() {
			BTNode root=new BTNode(1);
			root.Left=new BTNode(2);
			root.Right=new BTNode(3);
			BTNode p=root.Left;
			p.Left=new BTNode(4);
			p.Right=new BTNode(5);
			p=root.Right;
			p.Right=new BTNode(6);
			return root;
		}
		public static void ShowBinaryTree(BTNode root) {
			if(root==null) {
				System.out.println("This Binary tree is empty!");
				return;
			}
			int sum=0;//The total nodes
			Queue<BTNode> q=new LinkedList<BTNode>();
			q.add(root);
			int next=0;//Next level's nodes
			int count=1;//This level's nodes
			while(!q.isEmpty()) {
				if(count==0) {//This level's nodes has been printed 
					count=next;
					next=0;//reset next nodes
				}
				BTNode p=q.poll();
				count--;
				sum++;
				System.out.print(p.Data);
				if(p.Left!=null) {
					q.add(p.Left);
					next++;
				}
				if(p.Right!=null) {
					q.add(p.Right);
					next++;
				}
				if(count==0)System.out.println();
				else System.out.print(" ");
			}
			System.out.println(sum);
		}
	}
	public static void main(String[] args) {
		BTNode Root=BTNode.CreateBinaryTree();
		BTNode.ShowBinaryTree(Root);
	}
}

运行结果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值