https://www.geeksforgeeks.org/bfs-vs-dfs-binary-tree/

What are BFS and DFS for Binary Tree?
A Tree is typically traversed in two ways:

BFS and DFSs of above Tree

Breadth First Traversal : 1 2 3 4 5

Depth First Traversals:
Preorder Traversal : 1 2 4 5 3
Inorder Traversal : 4 2 5 1 3
Postorder Traversal : 4 5 2 3 1

Why do we care?
There are many tree questions that can be solved using any of the above four traversals. Examples of such questions are size, maximum, minimum, print left view, etc.

Is there any difference in terms of Time Complexity?
All four traversals require O(n) time as they visit every node exactly once.

Is there any difference in terms of Extra Space?
There is difference in terms of extra space required.

  1. Extra Space required for Level Order Traversal is O(w) where w is maximum width of Binary Tree. In level order traversal, queue one by one stores nodes of different level.
  2. Extra Space required for Depth First Traversals is O(h) where h is maximum height of Binary Tree. In Depth First Traversals, stack (or function call stack) stores all ancestors of a node.

Maximum Width of a Binary Tree at depth (or height) h can be 2h where h starts from 0. So the maximum number of nodes can be at the last level. And worst case occurs when Binary Tree is a perfect Binary Tree with numbers of nodes like 1, 3, 7, 15, …etc. In worst case, value of 2h is Ceil(n/2).

Height for a Balanced Binary Tree is O(Log n). Worst case occurs for skewed歪斜的 tree and worst case height becomes O(n).

So in worst case extra space required is O(n) for both. But worst cases occur for different types of trees.

It is evident from above points that extra space required for Level order traversal is likely to be more when tree is more balanced and extra space for Depth First Traversal is likely to be more when tree is less balanced.

How to Pick One?

  1. Extra Space can be one factor (Explained above)
  2. Depth First Traversals are typically recursive and recursive code requires function call overheads.
  3. The most important points is, BFS starts visiting nodes from root while DFS starts visiting nodes from leaves. So if our problem is to search something that is more likely to closer to root, we would prefer BFS. And if the target node is close to a leaf, we would prefer DFS.

Exercise:
Which traversal should be used to print leaves of Binary Tree and why?
Which traversal should be used to print nodes at k’th level where k is much less than total number of levels?

This article is contributed by Dheeraj Gupta. This
Please write comments if you find anything incorrect, or you want to
share more information about the topic discussed above

二叉树的C#定义

public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right; public TreeNode(int x)
{
val = x;
}
}

广度优先的遍历C#实现

 public IList<IList<int>> LevelOrder(TreeNode root)
{
IList<IList<int>> result = new List<IList<int>>();
Queue<TreeNode> queue=new Queue<TreeNode>();
Enqueue(queue, root);
while (queue.Count > )
{
var node = queue.Dequeue();
Console.WriteLine(node.val);
Output.WriteLine(node.val.ToString());
Enqueue(queue, node.left);
Enqueue(queue, node.right);
} return result;
} private void Enqueue(Queue<TreeNode> tempQueue, TreeNode node)
{
if (node != null)
{
tempQueue.Enqueue(node);
}
}

BFS广度优先 vs DFS深度优先 for Binary Tree的更多相关文章

  1. DFS+BFS(广度优先搜索弥补深度优先搜索遍历漏洞求合格条件总数)--09--DFS+BFS--蓝桥杯剪邮票

    题目描述 如下图, 有12张连在一起的12生肖的邮票.现在你要从中剪下5张来,要求必须是连着的.(仅仅连接一个角不算相连)  比如,下面两张图中,粉红色所示部分就是合格的剪取.  请你计算,一共有多少 ...

  2. 107. Binary Tree Level Order Traversal II

    题目: Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from ...

  3. 【LeetCode】102. Binary Tree Level Order Traversal 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS BFS 日期 题目描述 Given a bi ...

  4. 【leetcode❤python】102. Binary Tree Level Order Traversal

    #-*- coding: UTF-8 -*-#广度优先遍历# Definition for a binary tree node.# class TreeNode(object):#     def ...

  5. 【Binary Tree Right Side View 】cpp

    题目: Given a binary tree, imagine yourself standing on the right side of it, return the values of the ...

  6. LeetCode Binary Tree Right Side View (DFS/BFS)

    题意: 给一棵二叉树,要求收集每层的最后一个节点的值.按从顶到底装进vector返回. 思路: BFS比较简单,先遍历右孩子就行了. /** * Definition for a binary tre ...

  7. HDU 1241 Oil Deposits DFS(深度优先搜索) 和 BFS(广度优先搜索)

    Oil Deposits Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total ...

  8. HDU 4707 Pet(DFS(深度优先搜索)+BFS(广度优先搜索))

    Pet Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submissio ...

  9. (二叉树 BFS DFS) leetcode 104. Maximum Depth of Binary Tree

    Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the long ...

随机推荐

  1. html5-块元素和内联元素

    <!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8&qu ...

  2. Permutation Bo (数学证明)

    当在两端时:共有n * (n - 1)种组合,满足条件的有,计算可得, counter = n * (n - 1) / 2. 其他位置时:共有n * (n - 1) * (n - 2) 种组合,满足条 ...

  3. win7 64位 python启动报错:无法启动此程序,因为计算机中丢失api-ms-win-crt-process-l1-1-0.dll

    安装python3.7,安装成功后,在cmd窗口输入python检查是否安装成功,报错:无法启动此程序,因为计算机中丢失api-ms-win-crt-process-l1-1-0.dll 在网上查询了 ...

  4. Spring源码阅读(八)

    摘要: 本文首先将举例说明如何使用BeanWrapper,然后根据例子中的结果分析BeanWrapper的源码.由于在spring中BeanWrapperImpl是BeanWrapper接口的唯一实现 ...

  5. Go语言专题

    基础语法 Go语言配置开发环境 Go语言语法基础 Go语言面向对象 Go语言并发编程 Go语言搭建开发环境 语言库 Go语言fmt包 Go语言字节处理 Go语言字符串处理 Go语言JSON处理 Go语 ...

  6. ETL面试题集锦

    1. What is a logical data mapping and what does it mean to the ETL team? 什么是逻辑数据映射?它对ETL项目组的作用是什么? 答 ...

  7. centos-ftp搭建

    参照https://blog.csdn.net/a735834365/article/details/80622105 https://blog.csdn.net/a735834365/article ...

  8. 关于Ajax无法下载文件到浏览器本地的问题

    最近在做网站的时候遇到这样一个功能,在如图所示的页面中,需要用户点击链接的时候,能够以异步Ajax的方式判断服务器中是否存储有相应的Excel文件,如果没有的话就提示用户没有找到,如果有的话就下载到用 ...

  9. The Little Prince-12/03

    The Little Prince-12/03 These days, I am always busy with my things, including experiment and others ...

  10. VMware激活密钥

    VMware 2017 v14.x 永久许可证激活密钥FF31K-AHZD1-H8ETZ-8WWEZ-WUUVACV7T2-6WY5Q-48EWP-ZXY7X-QGUWD 原文链接