mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
更新 513.找树左下角的值 python 部分代码
1. 更改python 递归代码: 上一版本python代码跟卡哥思路不一样, 感觉把不同的解题方法放在这里不方便初学者学习. 所以建议更改. 2. 添加迭代方法代码.
This commit is contained in:
@ -274,8 +274,9 @@ class Solution {
|
|||||||
|
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
|
||||||
|
**递归法 - 回溯**
|
||||||
```python
|
```python
|
||||||
//递归法
|
|
||||||
# Definition for a binary tree node.
|
# Definition for a binary tree node.
|
||||||
# class TreeNode:
|
# class TreeNode:
|
||||||
# def __init__(self, val=0, left=None, right=None):
|
# def __init__(self, val=0, left=None, right=None):
|
||||||
@ -284,17 +285,53 @@ Python:
|
|||||||
# self.right = right
|
# self.right = right
|
||||||
class Solution:
|
class Solution:
|
||||||
def findBottomLeftValue(self, root: TreeNode) -> int:
|
def findBottomLeftValue(self, root: TreeNode) -> int:
|
||||||
depth=0
|
max_depth = -float("INF")
|
||||||
self.res=[]
|
max_left_value = -float("INF")
|
||||||
def level(root,depth):
|
|
||||||
if not root:return
|
def __traversal(root, left_len):
|
||||||
if depth==len(self.res):
|
nonlocal max_depth, max_left_value
|
||||||
self.res.append([])
|
|
||||||
self.res[depth].append(root.val)
|
if not root.left and not root.right:
|
||||||
level(root.left,depth+1)
|
if left_len > max_depth:
|
||||||
level(root.right,depth+1)
|
max_depth = left_len
|
||||||
level(root,depth)
|
max_left_value = root.val
|
||||||
return self.res[-1][0]
|
return
|
||||||
|
|
||||||
|
if root.left:
|
||||||
|
left_len += 1
|
||||||
|
__traversal(root.left, left_len)
|
||||||
|
left_len -= 1
|
||||||
|
|
||||||
|
if root.right:
|
||||||
|
left_len += 1
|
||||||
|
__traversal(root.right, left_len)
|
||||||
|
left_len -= 1
|
||||||
|
return
|
||||||
|
|
||||||
|
__traversal(root, 0)
|
||||||
|
|
||||||
|
return max_left_value
|
||||||
|
```
|
||||||
|
|
||||||
|
**迭代法 - 层序遍历**
|
||||||
|
```python
|
||||||
|
class Solution:
|
||||||
|
def findBottomLeftValue(self, root: TreeNode) -> int:
|
||||||
|
queue = deque()
|
||||||
|
if root:
|
||||||
|
queue.append(root)
|
||||||
|
result = 0
|
||||||
|
while queue:
|
||||||
|
q_len = len(queue)
|
||||||
|
for i in range(q_len):
|
||||||
|
if i == 0:
|
||||||
|
result = queue[i].val
|
||||||
|
cur = queue.popleft()
|
||||||
|
if cur.left:
|
||||||
|
queue.append(cur.left)
|
||||||
|
if cur.right:
|
||||||
|
queue.append(cur.right)
|
||||||
|
return result
|
||||||
```
|
```
|
||||||
Go:
|
Go:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user