深度优先(借助栈):
Depth First Search,对每一个分支路径深入到不能再深入为止,如图所示的二叉树遍历结果为:ABDECFHG
private static void dfs(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode peek = stack.peek();
System.out.println(peek.value + "\t");
stack.pop();
if (peek.right != null) stack.push(peek.right);//如果想从左边遍历先将右节点入栈,这样第二次while栈顶就是左节点
if (peek.left != null) stack.push(peek.left);
}
}
广度优先(借助队列):
Breadth First Search,横向优先搜索,是从根结点开始沿着树的宽度搜索遍历,上面二叉树的遍历顺序为:ABCDEFG,类似于层序遍历。
private static void bfs(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode peek = queue.poll();
System.out.println(peek.value + "\t");
if (peek.left != null) queue.offer(peek.left);
if (peek.right != null) queue.offer(peek.right);
}
}