bfs 二叉树 遍历

bfs 遍历二叉树

之前只知道bfs 的思想以及需要使用队列来进行存储

为了更好的理解bfs
手写了bfs 遍历二叉树的两种方式

方法:

一种是采用常用的递归执行
另一种是采用循环执行(使用栈来代替递归)

二叉树定义

class Node {
	//get set方法省略
	private Node leftChild;
	private Node rightChild;
	private int data;

	public Node(int data) {
		this.data = data;
	}
	
}

构造二叉树


Node node = new Node(1);

		node.setLeftChild(new Node(2));
		node.setRightChild(new Node(3));
		node.getLeftChild().setLeftChild(new Node(4));
		node.getLeftChild().setRightChild(new Node(5));
	
		bfs(node);

使用bfs

方式一:递归
public static void bfs(Node node) {
		if (node != null) {
			System.out.println(node.getData());
			if (node.getLeftChild() != null) {
				queue.add(node.getLeftChild());
			}
			if (node.getRightChild() != null) {
				queue.add(node.getRightChild());
			}
		}
		if(!queue.isEmpty()){
			bfs(queue.remove());
		}
	}
方式二:循环
public static void bfsUseLoop(Node node) {
		queue.add(node);
		while (!queue.isEmpty()) {

			Node remove = queue.remove();
			System.out.println(remove.getData());
			if (remove.getLeftChild() != null) {
				queue.add(remove.getLeftChild());
			}
			if (remove.getRightChild() != null) {
				queue.add(remove.getRightChild());
			}
		}
	}

参考文章

数据结构—递归与非递归实现DFS与BFS

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中的二叉树可以使用广度优先搜索(BFS)和深度优先搜索(DFS)两种方法。 BFS(广度优先搜索)是一种逐层遍叉树的方法。从根节点开始,按照层级顺序依次访问每个节点,先访问左子节点,再访问右子节点。具体实现可以使用队列来辅助实现。以下是BFS的实现方式: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def bfs(root): if not root: return [] queue = [root] result = [] while queue: node = queue.pop(0) result.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) return result ``` DFS(深度优先搜索)是一种先访问根节点,然后递归地访问左子树和右子树的方法。DFS有三种常见的遍方式:前序遍、中序遍和后序遍。以下是DFS的实现方式: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def dfs_preorder(root): if not root: return [] result = [] result.append(root.val) result += dfs_preorder(root.left) result += dfs_preorder(root.right) return result def dfs_inorder(root): if not root: return [] result = [] result += dfs_inorder(root.left) result.append(root.val) result += dfs_inorder(root.right) return result def dfs_postorder(root): if not root: return [] result = [] result += dfs_postorder(root.left) result += dfs_postorder(root.right) result.append(root.val) return result ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值