//深度优先遍历
private static void getDFS(TreeNode root) {
if (root == null) {
return;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode temp = stack.peek();
System.out.print(temp.value + "\t");
stack.pop();
//这里利用了堆的--先进后出的特性,所以右节点要在左节点前入堆,这里如果不好理解建议在Debug下,查看stack的变化内容就比较容易理解了
if (temp.right != null) {
stack.push(temp.right);
}
if (temp.left != null) {
stack.push(temp.left);
}
}
System.out.println("深度优先遍历结束");
}
```
//广度优先遍历
private static void getBFS(TreeNode root) {
// TODO Auto-generated method stub
if (root == null) {
return;
}
ArrayList<TreeNode> queue = new ArrayList<>();
queue.add(root);
while (queue.size() > 0) {
TreeNode temp = queue.get(0);
queue.remove(0);
System.out.print(temp.value + "\t");
//这里利用了队列的--先进先出的特性,所以左节点要在右节点前入堆,这里如果不好理解建议在Debug下,查看stack的变化内容就比较容易理解了
if (temp.left != null) {
queue.add(temp.left);
}
if (temp.right != null) {
queue.add(temp.right);
}
}
System.out.println("广度优先遍历结束");
}
用栈实现的深度优先/广度优先遍历
最新推荐文章于 2025-04-23 11:41:53 发布