树的层序遍历

一、思路:实现的数据结构无所谓,主要能保证是FIFO的效果就好。
层序遍历思路

二、实现

	package 树;
	
	public class Node<T> {
		public T data; // 节点数据
		public Node leftChild; // 左子节点的引用
		public Node rightChild; // 右子节点的引用
		
		public Node(T data) {
			this.data = data;
			// PS:经国良同学提醒,构造函数需要考虑左右子树的初始化
			this.leftChild = null;
			this.rightChild = null;
		}
	
		// 打印节点内容
		public void display() {
			System.out.println(data);
		}
}
	package 树;
	
	import java.util.ArrayList;
	import java.util.LinkedList;
	import java.util.List;
	import java.util.Queue;
	
	public class BFSTraversal2 {
		public static void main(String[] args) {
			Node<Integer> root = new Node<Integer>(3);
			Node<Integer> node2 = new Node<Integer>(1);
			Node<Integer> node3 = new Node<Integer>(2);
			Node<Integer> node4 = new Node<Integer>(5);
			Node<Integer> node5 = new Node<Integer>(4);
			root.leftChild = node2;
			root.rightChild = node3;
			node2.leftChild = node4;
			node2.rightChild = node5;
			bfsTraversal3(root);
		}
		
		// 数组实现
		private static void bfsTraversal2(Node root) {
			if(root==null) return;
			List<Node> list = new ArrayList<>();
			list.add(root);
			Node node;
			while(!list.isEmpty()) {
				node = list.get(0);
				node.display();
				list.remove(0);
				if(node.leftChild!=null) {
					list.add(node.leftChild);
				}
				if(node.rightChild!=null) {
					list.add(node.rightChild);
				}
			}
		}
		
		// 队列实现
		private static void bfsTraversal3(Node root) {
			if(root==null) return;
			Queue<Node> queue = new LinkedList<Node>();
			queue.add(root);
			Node node;
			while(!queue.isEmpty()) {
				node = queue.poll();
				node.display();
				if(node.leftChild!=null) {
					queue.add(node.leftChild);
				}
				if(node.rightChild!=null) {
					queue.add(node.rightChild);
				}
			}
		}
	}

三、疑惑
Queue和LinkedList什么关系?

猜你喜欢

转载自blog.csdn.net/zyd196504/article/details/82866248
今日推荐