宽度优先搜索python_怎么用Python写一个广度优先算法?

请看LeetCode 上的一个题目Loading...​leetcode.comv2-0c435ab948b151fd834be55f80a09794_180x120.jpg

第一, Python 代码, 用非递归遍历,题目已经假定了root 非空, 用队列(Python 用list 模拟队列),先添加root到队列中,出队列,再判右子树不为空,就添加右子树,再判断左子树是不是为空,非空添加左子树。

# Definition for a binary tree node.

# class TreeNode:

# def __init__(self, x):

# self.val = x

# self.left = None

# self.right = None

class Solution:

'''黄哥Python培训 黄哥所写'''

def findBottomLeftValue(self, root: TreeNode) -> int:

res = root.val

q = [root]

while q:

node = q.pop(0)

res = node.val

if node.right:

q.append(node.right)

if node.left:

q.append(node.left)

return res

第二,Go 语言代码,用的递归,原因是Go 中slice 不好模拟队列,就用递归来写,先求树的高度,再写bfs,bfs一定要先调用右子树,再左子树,bfs 传三个参数,root, res 用指针返回值,还有一个是层level。

/**

* Definition for a binary tree node.

* type TreeNode struct {

* Val int

* Left *TreeNode

* Right *TreeNode

* }

*/

// 黄哥Python培训 黄哥所写

func findBottomLeftValue(root *TreeNode) int {

var res int

bfs(root, &res, height(root))

return res

}

func bfs(root *TreeNode, res *int, level int) {

if root == nil {

return

}

if level == 1 {

*res = root.Val

}else if level > 1 {

bfs(root.Right, res, level - 1)

bfs(root.Left, res, level - 1)

}

}

func height(root *TreeNode) int {

if root == nil {

return 0

}

return int(math.Max(float64(height(root.Left)), float64(height(root.Right)))) + 1

}

第三,用Java 实现。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值