Python实现深度遍历和广度遍历的方法
作者:纳尔逊皮卡丘 时间:2023-10-13 20:41:13
深度遍历:
原则:从上到下,从左到右
逻辑(本质用递归):
1)、找根节点
2)、找根节点的左边
3)、找根节点的右边
class Node(object):
def __init__(self, item=None, left=None, right=None):
self.item = item
self.left = left
self.right = right
d = Node("D")
e = Node("E")
b = Node("B", d, e)
f = Node("F")
g = Node("G")
c = Node("C", f, g)
a = Node("A", b, c)
result = []
def deep_search(root):
# 深度遍历 核心:递归
result.append(root.item)
if root.left:
deep_search(root.left)
if root.right:
deep_search(root.right)
return "-->".join(result)
print deep_search(a)
广度遍历:
核心:队列+递归
def wide_search(root, result=[]):
if not result:
result.append(root.item)
if root.left:
result.append(root.left.item)
if root.right:
result.append(root.right.item)
if root.left:
wide_search(root.left)
if root.right:
wide_search(root.right)
return "-->".join(result)
print wide_search(a)
来源:https://blog.csdn.net/zhaobig/article/details/78649059
标签:Python,深度,遍历,广度
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
java连接mysql数据库乱码的解决方法
2024-01-21 06:26:15
JavaScript给数组添加元素的6个方法
2024-04-30 08:46:47
Python自动化办公之创建PPT文件
2022-01-16 19:31:49
![](https://img.aspxhome.com/file/2023/0/131610_0s.jpg)
安装sql server 2008 management提示已安装 SQL Server 2005 Express的解决方法
2024-01-15 12:49:03
php 文件缓存函数
2023-11-06 15:28:47
Python程序设计入门(3)数组的使用
2023-07-20 07:11:15
ASP.NET将Session保存到数据库中的方法
2024-01-19 16:31:46
Pandas之缺失数据的实现
2022-05-04 19:00:05
![](https://img.aspxhome.com/file/2023/9/115099_0s.png)
Python利用pythonping处理ping的示例详解
2023-08-12 00:28:45
![](https://img.aspxhome.com/file/2023/0/128730_0s.png)
Python 二分查找之bisect库的使用详解
2023-10-03 01:24:29
Python脚本操作Excel实现批量替换功能
2023-06-15 16:37:57
![](https://img.aspxhome.com/file/2023/3/75933_0s.jpg)
使用Selenium实现微博爬虫(预登录、展开全文、翻页)
2022-07-09 11:00:18
![](https://img.aspxhome.com/file/2023/2/107562_0s.jpg)
mac安装python3后使用pip和pip3的区别说明
2021-01-06 21:23:15
![](https://img.aspxhome.com/file/2023/3/77553_0s.jpg)
vue3和ts封装axios以及使用mock.js详解
2024-04-28 09:27:47
![](https://img.aspxhome.com/file/2023/5/132955_0s.png)
MYSQL常用命令与实用技巧
2024-01-22 05:22:25
基于Vue3实现印章徽章组件的示例代码
2023-07-02 16:54:28
![](https://img.aspxhome.com/file/2023/4/139814_0s.png)
Python基于内置函数type创建新类型
2023-11-18 10:00:29
详解如何创建并发布一个 vue 组件
2023-07-02 16:49:08
![](https://img.aspxhome.com/file/2023/0/139790_0s.gif)
在MySQL中使用LIMIT进行分页的方法
2024-01-20 22:27:58
如何使用pyinstaller打包32位的exe程序
2021-12-17 10:15:20
![](https://img.aspxhome.com/file/2023/2/86362_0s.png)