513. 找树左下角的值
给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。
假设二叉树中至少有一个节点。
示例 1:
输入: root = [2,1,3]
输出: 1
示例 2:
输入: [1,2,3,4,null,5,6,null,null,7]
输出: 7
提示:
二叉树的节点个数的范围是 [1,104]
-231 <= Node.val <= 231 - 1
方法1:BFS
public int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
TreeNode res = root;
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
if (i == 0) res = q.peek();
TreeNode cur = q.poll();
if (cur.left != null) q.offer(cur.left);
if (cur.right != null) q.offer(cur.right);
}
}
return res.val;
}
方法2:DFS
- 先左子树节点后右子树节点,左子树切换到右子树的时机进行最大深度
maxDepth
的更新与记录,并保存结果值
public int findBottomLeftValue(TreeNode root) {
dfs(root, 0);
return res;
}
int maxDepth = -1, res = 0;
private void dfs(TreeNode root, int depth) {
if (root == null) return;
dfs(root.left, depth + 1);
if (depth > maxDepth) {
maxDepth = depth;
res = root.val;
}
dfs(root.right, depth + 1);
}
Follow Up:找树右下角的值
方法1:BFS
public int findBottomRightValue(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
TreeNode res = root;
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
if (i == size - 1) res = q.peek();
TreeNode cur = q.poll();
if (cur.left != null) q.offer(cur.left);
if (cur.right != null) q.offer(cur.right);
}
}
return res.val;
}
方法2:DFS
public int findBottomRightValue(TreeNode root) {
dfs(root, 0);
return res;
}
int maxDepth = -1, res = 0;
private void dfs(TreeNode root, int depth) {
if (root == null) return;
dfs(root.right, depth + 1);
if (depth > maxDepth) {
maxDepth = depth;
res = root.val;
}
dfs(root.left, depth + 1);
}