树的BFS

本文介绍了一种优化广度优先搜索(BFS)的方法,以减少在遍历树过程中内存的使用。当树的深度增加时,传统BFS可能会导致内存消耗翻倍。为了解决这个问题,提出了一种策略,即牺牲一些时间来换取更少的内存使用。通过在遍历过程中使用特定标志来指示层级变化,可以在内存受限的情况下有效地遍历树。
摘要由CSDN通过智能技术生成

public class BFS {

	public static void bfs(Node root){
		if(root == null){
			return;
		}
		Queue queue = new Queue();
		queue.poll(root);
		queue.poll(new Node("flag"));
		
		while(queue.peek() != null){
			Node node = (Node)queue.offer();
			if(node.id == null){
				System.out.print(node.value + " ");
				if(node.left != null){
					queue.poll(node.left);
				}
				if(node.right != null){
					queue.poll(node.right);
				}
			}else{
				if(!queue.isEmpty()){
					queue.poll(new Node("flag"));
					System.out.println();
				}
			}
		}
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		BinaryTree bt = new BinaryTree();
		int[] a = {7,2,4,8,3,5,1,9,0,6};
		bt.buildTree(a);
		bt.printTree();
		
		BFS.bfs(bt.root);

	}

}

上面的方法,至少需要保存某一层的节点,随着树的增长,消耗的内存会翻倍增长,如果内存受限,怎样做。
迭代搜索。内存取决于树的深度。牺牲时间换空间。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值