返回
LeetCode513题,找树左下角的值
前端
2023-10-19 06:25:07
题目分析
这道题的题目得很清楚,我们要做的就是找到给定二叉树中最左下角的值。那么,我们首先要明确一个概念:什么是最左下角的值?
最左下角的值,是指在二叉树的最后一行中,最左边的值。也就是说,我们要找到二叉树的最左边的叶子节点。
解题思路
既然我们要找二叉树的最左边的叶子节点,那么我们可以采用深度优先搜索(DFS)或者广度优先搜索(BFS)来解决这道题。
DFS解法
DFS的解法很简单,我们可以先找到二叉树的根节点,然后依次遍历根节点的左子树和右子树。在遍历左子树和右子树的时候,我们要注意的是,我们只遍历最左边的子节点。也就是说,我们在遍历左子树的时候,我们只遍历左子树的最左边的子节点,而在遍历右子树的时候,我们只遍历右子树的最左边的子节点。
这样,我们就可以找到二叉树的最左边的叶子节点,也就是二叉树的最左下角的值。
BFS解法
BFS的解法也比较简单,我们可以先把二叉树的根节点放入一个队列中。然后,我们依次从队列中取出节点,并遍历该节点的左子树和右子树。在遍历左子树和右子树的时候,我们要注意的是,我们只遍历最左边的子节点。也就是说,我们在遍历左子树的时候,我们只遍历左子树的最左边的子节点,而在遍历右子树的时候,我们只遍历右子树的最左边的子节点。
这样,我们就可以找到二叉树的最左边的叶子节点,也就是二叉树的最左下角的值。
代码实现
def find_bottom_left_value(root):
"""
Finds the value of the leftmost node in the last row of a binary tree.
Args:
root: The root node of the binary tree.
Returns:
The value of the leftmost node in the last row of the binary tree.
"""
# If the root node is None, then the tree is empty and there is no leftmost node in the last row.
if root is None:
return None
# Create a queue to store the nodes of the binary tree.
queue = [root]
# While the queue is not empty, do the following:
while queue:
# Get the number of nodes in the current level of the binary tree.
level_size = len(queue)
# For each node in the current level of the binary tree, do the following:
for _ in range(level_size):
# Get the current node from the queue.
node = queue.pop(0)
# If the current node is a leaf node, then it is the leftmost node in the last row of the binary tree.
if not node.left and not node.right:
return node.val
# If the current node has a left child, then add the left child to the queue.
if node.left:
queue.append(node.left)
# If the current node has a right child, then add the right child to the queue.
if node.right:
queue.append(node.right)
# If the queue is empty, then the tree is empty and there is no leftmost node in the last row.
return None
总结
这道题的解法并不难,但还是有一些技巧的。我们在解这道题的时候,要注意的是,我们要只遍历最左边的子节点。这样,我们就可以找到二叉树的最左边的叶子节点,也就是二叉树的最左下角的值。