BFS广度优先 vs DFS深度优先 for Binary Tree
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:
- Breadth First Traversal (Or Level Order Traversal)
- Depth First Traversals
- Inorder Traversal (Left-Root-Right)
- Preorder Traversal (Root-Left-Right)
- Postorder Traversal (Left-Right-Root)
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.
- 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.
- 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?
- Extra Space can be one factor (Explained above)
- Depth First Traversals are typically recursive and recursive code requires function call overheads.
- 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的更多相关文章
- DFS+BFS(广度优先搜索弥补深度优先搜索遍历漏洞求合格条件总数)--09--DFS+BFS--蓝桥杯剪邮票
题目描述 如下图, 有12张连在一起的12生肖的邮票.现在你要从中剪下5张来,要求必须是连着的.(仅仅连接一个角不算相连) 比如,下面两张图中,粉红色所示部分就是合格的剪取. 请你计算,一共有多少 ...
- 107. Binary Tree Level Order Traversal II
题目: Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from ...
- 【LeetCode】102. Binary Tree Level Order Traversal 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS BFS 日期 题目描述 Given a bi ...
- 【leetcode❤python】102. Binary Tree Level Order Traversal
#-*- coding: UTF-8 -*-#广度优先遍历# Definition for a binary tree node.# class TreeNode(object):# def ...
- 【Binary Tree Right Side View 】cpp
题目: Given a binary tree, imagine yourself standing on the right side of it, return the values of the ...
- LeetCode Binary Tree Right Side View (DFS/BFS)
题意: 给一棵二叉树,要求收集每层的最后一个节点的值.按从顶到底装进vector返回. 思路: BFS比较简单,先遍历右孩子就行了. /** * Definition for a binary tre ...
- HDU 1241 Oil Deposits DFS(深度优先搜索) 和 BFS(广度优先搜索)
Oil Deposits Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total ...
- HDU 4707 Pet(DFS(深度优先搜索)+BFS(广度优先搜索))
Pet Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submissio ...
- (二叉树 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 ...
随机推荐
- python selenium设置chrome的下载路径
python可以通过ChromeOptions设置chrome参数,如下载路径等,代码如下(python 3.6.7): #-*-coding=utf-8-*- from selenium impor ...
- 微信小程序制作家庭记账本之五
第五天,开发进度没有进行,不知道该如何下手完成小程序的开发.
- Linux基础命令---删除用户userdel
userdel 删除用户,如果没有附加选项,仅删除用户,不删除相关文件. 此命令的适用范围:RedHat.RHEL.Ubuntu.CentOS.SUSE.openSUSE.Fedora. 1.语法 ...
- 设置 DNS,防止 DNS 污染,清除 DNS 缓存ipconfig /flushdns
设置 DNS,防止 DNS 污染选中“使用下面的 DNS 服务器地址”,“首选 DNS 服务器”中填写 8.8.8.8,“备用 DNS 服务器”中填写 8.8.4.4,然后点击“确定”按钮清除 DNS ...
- [转载]css3的一个控制背景的属性,background-size可以缩放大小啦
background-size需要两个值,它的类型可以是像素(px).百分比(%)或是auto,还可以是cover和contain.第一个值为背景图的width,另外一个值用于指定背景图上的heigh ...
- System.map文件的作用解析
有关System.map文件的信息好象很缺乏.其实它一点也不神秘,并且在整个事情当中它并不象看上去那么得重要.但是由于缺乏必要的文档说明,使其显得比较神秘.它就象耳垂,我们每个人都有,但却不知道是干什 ...
- Django框架----视图(views)
Django的Views(视图) 一个视图函数(类),简称视图,是一个简单的Python 函数(类),它接受Web请求并且返回Web响应. 响应可以是一张网页的HTML内容,一个重定向,一个404错误 ...
- linux centos6.5 php5.6 安装PHPUnit 5.2.9 (转)
转自:http://blog.csdn.net/shancunxiaoyazhi/article/details/50765293 操作系统版本:CentOS6.5 PHP版本:5.6 下载phpun ...
- Let's Encrypt申请证书及使用
Let's Encrypt是一个免费的.自动的,开放的CA. 形形色色有证书扩展名和类型,我是通过这篇文章明白个大体的:http://www.cnblogs.com/guogangj/p/411860 ...
- 【视频】使用fiddler开发工具进行新架构页面本地调试
[视频]使用fiddler开发工具进行新架构页面本地调试,视频没录制好,有些部分比较模糊...