Merge pull request #622 from shuwenlan/master

添加 层序遍历中的 104. 二叉树的最大深度 Python版本
This commit is contained in:
程序员Carl
2021-08-20 08:23:43 +08:00
committed by GitHub

View File

@ -1532,6 +1532,29 @@ Java
Python
```python 3
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root == None:
return 0
queue_ = [root]
result = []
while queue_:
length = len(queue_)
sub = []
for i in range(length):
cur = queue_.pop(0)
sub.append(cur.val)
#子节点入队列
if cur.left: queue_.append(cur.left)
if cur.right: queue_.append(cur.right)
result.append(sub)
return len(result)
```
Go
@ -1539,6 +1562,8 @@ JavaScript
# 111.二叉树的最小深度
题目地址https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
相对于 104.二叉树的最大深度 ,本题还也可以使用层序遍历的方式来解决,思路是一样的。
**需要注意的是,只有当左右孩子都为空的时候,才说明遍历的最低点了。如果其中一个孩子为空则不是最低点**
@ -1574,7 +1599,35 @@ public:
Java
Python
Python 3
```python 3
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDepth(self, root: TreeNode) -> int:
if root == None:
return 0
#根节点的深度为1
queue_ = [(root,1)]
while queue_:
cur, depth = queue_.pop(0)
if cur.left == None and cur.right == None:
return depth
#先左子节点,由于左子节点没有孩子,则就是这一层了
if cur.left:
queue_.append((cur.left,depth + 1))
if cur.right:
queue_.append((cur.right,depth + 1))
return 0
```
Go