欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

深度优先搜索和广度优先搜索

程序员文章站 2022-05-22 20:22:42
...
/**
 * BFS:利用队列
 */
public static List<Integer> bfs(TreeNode root) {
	Queue<TreeNode> treeNodeQueue = new LinkedList<>();
	List<Integer> integerList = new ArrayList<>();
	if (root == null) return new ArrayList<>();
	((LinkedList<TreeNode>) treeNodeQueue).add(root);
	while (!treeNodeQueue.isEmpty()) {
		TreeNode treeNode = treeNodeQueue.poll();
		integerList.add(treeNode.val);
		if (treeNode.left != null) {
			((LinkedList<TreeNode>) treeNodeQueue).add(treeNode.left);
		}
		if (treeNode.right != null) {
			((LinkedList<TreeNode>) treeNodeQueue).add(treeNode.right);
		}
	}
	return integerList;
}
/**
 * DFS:先序遍历,非递归方式利用 栈
 */
public static List<Integer> dfs(TreeNode root) {
	Stack<TreeNode> treeNodeStack = new Stack<>();
	List<Integer> integerList = new ArrayList<>();
	if (root == null) return new ArrayList<>();
	treeNodeStack.add(root);
	while (!treeNodeStack.isEmpty()) {
		TreeNode treeNode = treeNodeStack.pop();
		integerList.add(treeNode.val);
		if (treeNode.right != null) treeNodeStack.add(treeNode.right);
		if (treeNode.left != null) treeNodeStack.add(treeNode.left);
	}
	return integerList;
}