mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Merge pull request #535 from KelvinG-611/513.找树左下角的值
更新 513.找树左下角的值 python部分代码
This commit is contained in:
@ -274,27 +274,51 @@ class Solution {
|
|||||||
|
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
|
||||||
|
**递归 - 回溯**
|
||||||
```python
|
```python
|
||||||
//递归法
|
|
||||||
# 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:
|
class Solution:
|
||||||
def findBottomLeftValue(self, root: TreeNode) -> int:
|
def findBottomLeftValue(self, root: TreeNode) -> int:
|
||||||
depth=0
|
max_depth = -float("INF")
|
||||||
self.res=[]
|
leftmost_val = 0
|
||||||
def level(root,depth):
|
|
||||||
if not root:return
|
def __traverse(root, cur_depth):
|
||||||
if depth==len(self.res):
|
nonlocal max_depth, leftmost_val
|
||||||
self.res.append([])
|
if not root.left and not root.right:
|
||||||
self.res[depth].append(root.val)
|
if cur_depth > max_depth:
|
||||||
level(root.left,depth+1)
|
max_depth = cur_depth
|
||||||
level(root.right,depth+1)
|
leftmost_val = root.val
|
||||||
level(root,depth)
|
if root.left:
|
||||||
return self.res[-1][0]
|
cur_depth += 1
|
||||||
|
__traverse(root.left, cur_depth)
|
||||||
|
cur_depth -= 1
|
||||||
|
if root.right:
|
||||||
|
cur_depth += 1
|
||||||
|
__traverse(root.right, cur_depth)
|
||||||
|
cur_depth -= 1
|
||||||
|
|
||||||
|
__traverse(root, 0)
|
||||||
|
return leftmost_val
|
||||||
|
```
|
||||||
|
**迭代 - 层序遍历**
|
||||||
|
```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