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. Nginx常用功能

    3.Nginx常用功能 3.1 反向代理服务器 3.1.1.demo2 a.我在tomcat下部署了一个javaweb项目,tomcat安装的服务器IP为:192.168.37.136,部署的项目在t ...

  2. 《大话设计模式》c++实现 外观模式

    外观模式:为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用. 外观模式在什么时候使用呢? 分为三个阶段: (1)首先,在设计初期阶段,应该要有意识的 ...

  3. 《大话设计模式》c++实现 原型模式

    意图:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象. 主要解决:在运行期建立和删除原型. 何时使用: 1.当一个系统应该独立于它的产品创建,构成和表示时. 2.当要实例化的类是在运行 ...

  4. JavaScript--将秒数换算成时分秒

    getTime()  返回距 1970 年 1 月 1 日之间的毫秒数 new Date(dateString) 定义 Date 对象的一种方式 <!DOCTYPE html> <h ...

  5. skynet 报错 skynet 服务缺陷 Lua死循环

    我的报错如下: 看起来是skynet中lua死循环,实际上,可能只是本地配置出了问题,比如,我的数据库连接不上了,因为我把别人的配置更新到我本地了,吗,mysql秘密不对 解决办法就是将配置文件中的, ...

  6. svn安装使用

    SVN安装使用 获取项目 1.首先新建文件夹.如:测试项目. 2.接着鼠标右键选择:SVN Checkout/SVN 检出 3.在出行的对话框中输入仓库地址.如:svn://198.021.262/2 ...

  7. 微信小程序制作家庭记账本之七

    最后一天,程序完成的仍然不是很好,作品很简陋,不过还是可以记账的,没有购买域名,别人无法使用,下次我会完成的更好.

  8. 微信小程序制作家庭记账本之六

    第六天,自己根据样本代码做的记账本可实现添加账目,删除账目和消费总和,实机可以测试,但是没有域名,别人无法访问.

  9. ActiveMQ任意文件写入漏洞(版本在5.12.X前CVE-2016-3088)

    ActiveMQ任意文件写入漏洞(版本在5.12.X前CVE-2016-3088) 查看docker的activemq版本命令:$ docker ps | grep activemq927860512 ...

  10. .net core创建项目(指令方式)

    所谓的指令创建项目,就是不用再已安装的VS2015的环境下或者VS Core下创建,直接通过DOS指令创建也是OK的. 1.找到你所准备保存项目的项目文件夹(你也可以到某个目录用指令创建项目文件夹[  ...