https://leetcode.cn/problems/LwUNpT/
https://leetcode.cn/problems/find-bottom-left-tree-value/
难度:☆☆☆
题目:
给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。假设二叉树中至少有一个节点。
示例:
输入: root = [2,1,3]
输出: 1
方法1:深度优先搜索BFS
Python
class Solution:
def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
curval, curheight = 0, 0
def dfs(node, height):
nonlocal curval, curheight
if not node:
return
height += 1
dfs(node.left, height)
dfs(node.right, height)
if height > curheight:
curheight = height
curval = node.val
dfs(root, 0)
return curval
Java
class Solution {
int curVal = 0;
int curHeight = 0;
public int findBottomLeftValue(TreeNode root) {
dfs(root, 0);
return curVal;
}
public void dfs(TreeNode node, int height) {
if (node == null) {
return;
}
height++;
dfs(node.left, height);
dfs(node.right, height);
if (height > curHeight) {
curHeight = height;
curVal = node.val;
}
}
}
方法2:广度优先搜索DFS
使用广度优先搜索遍历每一层的节点。
在遍历一个节点时,需要先把它的非空右子节点放入队列,然后再把它的非空左子节点放入队列,
这样才能保证广度优先搜索所遍历的最后一个节点的值就是最底层最左边节点的值。
Python
class Solution:
def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
from collections import deque
ans = 0
q = deque([root])
while q:
node = q.popleft()
if node.right:
q.append(node.right)
if node.left:
q.append(node.left)
ans = node.val
return ans
Java
class Solution {
public int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> queue = new ArrayDeque<>();
int ans = 0;
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node.right != null) {
queue.offer(node.right);
}
if (node.left != null) {
queue.offer(node.left);
}
ans = node.val;
}
return ans;
}
}