原题链接:
https://leetcode.cn/problems/find-bottom-left-tree-value/description/
完成情况:
解题思路:
_513找树左下角的值_dfs记录高度
package leetcode板块;
public class _513找树左下角的值_dfs记录高度 {
private class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
private int value = 0;
private int height = 0;
/**
*
* @param root
* @return
*/
public int findBottomLeftValue(TreeNode root) {
// TODO 找一棵树最下层,并且最左边的值
//全局化变量,避免函数调用中引入太多的参数
dfs_findBottomLeftValue(root,0);
return value;
}
/**
*
* @param root
* @param curHeight
*/
private void dfs_findBottomLeftValue(TreeNode root, int curHeight) {
if (root == null){
return;
}
curHeight++;
dfs_findBottomLeftValue(root.left,curHeight);
dfs_findBottomLeftValue(root.right,curHeight);
if (curHeight > height){ //说明当前左值,满足我需要找的条件
height = curHeight;
value = root.val;
}
}
}
_513找树左下角的值_bfs层次最左
package leetcode板块;
import java.util.ArrayDeque;
import java.util.Queue;
public class _513找树左下角的值_bfs层次最左 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
/**
*
* @param root
* @return
*/
public int findBottomLeftValue(TreeNode root){
int result = 0;
Queue<TreeNode> myQueue = new ArrayDeque<TreeNode>();
myQueue.offer(root);
while (!myQueue.isEmpty()){
TreeNode curNode = myQueue.poll();
// 我先存储右边,再存储左边,那么最后一个返回出来的必然就是整颗树的最左边元素
if (curNode.right != null){
myQueue.offer(curNode.right);
}
if (curNode.left != null){
myQueue.offer(curNode.left);
}
result = curNode.val;
}
return result;
}
}
参考代码:
_513找树左下角的值_dfs记录高度
Sure, let me explain the code provided in detail.
Overview
The code defines a class to solve the problem of finding the bottom-left value in a binary tree using depth-first search (DFS). The code includes an inner class TreeNode
representing a node in the tree and the main logic to find the bottom-left value.
Class Definitions
- TreeNode Class:
- Represents a node in a binary tree.
- Contains three fields:
val
(the value of the node),left
(reference to the left child), andright
(reference to the right child). - Includes three constructors:
- Default constructor initializing an empty node.
- Constructor initializing a node with a given value.
- Constructor initializing a node with a given value, left child, and right child.
Main Logic
- _513找树左下角的值_dfs记录高度 Class:
- Contains the main logic to find the bottom-left value in the tree.
- Uses two instance variables:
value
to store the value of the bottom-left node.height
to store the maximum height reached during the DFS traversal.
- The
findBottomLeftValue
method:- Takes the root of the tree as input.
- Calls the helper method
dfs_findBottomLeftValue
to perform DFS traversal. - Returns the value of the bottom-left node.
- The
dfs_findBottomLeftValue
method:- Takes a node (
root
) and the current height (curHeight
) as input. - Performs DFS traversal, incrementing
curHeight
at each level. - Checks if the current node is deeper than any previously visited nodes (
curHeight > height
). If so, updatesheight
andvalue
.
- Takes a node (
Explanation of dfs_findBottomLeftValue
Method
- Base Case: If the current node (
root
) is null, return immediately. This prevents further traversal down a non-existent path. - Recursive Case:
- Increment
curHeight
to reflect moving down one level in the tree. - First, recursively call the method on the left child (
root.left
). This ensures that left-most nodes are visited first. - Then, recursively call the method on the right child (
root.right
). - After the recursive calls, check if the current node’s height (
curHeight
) is greater than the maximum height encountered so far (height
). If true, updateheight
and setvalue
to the current node’s value (root.val
).
- Increment
Corrected Implementation
However, there is a logical error in your current implementation: the if (curHeight > height)
condition should be checked before the recursive calls to ensure that the left-most node is correctly identified.
Here’s the corrected implementation:
package leetcode板块;
public class _513找树左下角的值_dfs记录高度 {
private class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
private int value = 0;
private int height = 0;
public int findBottomLeftValue(TreeNode root) {
dfs_findBottomLeftValue(root, 0);
return value;
}
private void dfs_findBottomLeftValue(TreeNode root, int curHeight) {
if (root == null) {
return;
}
curHeight++;
if (curHeight > height) { // Check height before recursive calls
height = curHeight;
value = root.val;
}
dfs_findBottomLeftValue(root.left, curHeight);
dfs_findBottomLeftValue(root.right, curHeight);
}
}
Summary
- The
dfs_findBottomLeftValue
method performs a DFS traversal to find the left-most node at the maximum depth. - The height is checked and updated before making recursive calls to ensure that the left-most node at each level is correctly identified.
_513找树左下角的值_bfs层次最左
Sure, let’s go through the BFS implementation for finding the bottom-left value of a binary tree step by step.
Overview
The code defines a class to solve the problem of finding the bottom-left value in a binary tree using breadth-first search (BFS). This approach uses a queue to traverse the tree level by level from right to left. The last node encountered during this traversal will be the bottom-left node.
Class Definitions
- TreeNode Class:
- Represents a node in a binary tree.
- Contains three fields:
val
(the value of the node),left
(reference to the left child), andright
(reference to the right child). - Includes three constructors:
- Default constructor initializing an empty node.
- Constructor initializing a node with a given value.
- Constructor initializing a node with a given value, left child, and right child.
Main Logic
- _513找树左下角的值_bfs层次最左 Class:
- Contains the main logic to find the bottom-left value in the tree.
- The
findBottomLeftValue
method:- Takes the root of the tree as input.
- Uses a queue (
myQueue
) to perform BFS traversal. - Returns the value of the bottom-left node.
Explanation of findBottomLeftValue
Method
- Initialization:
- Initialize
result
to store the bottom-left value. - Create a queue (
myQueue
) and add the root node to it.
- Initialize
- BFS Traversal:
- While the queue is not empty:
- Poll the current node (
curNode
) from the front of the queue. - Add the right child (
curNode.right
) to the queue if it exists. - Add the left child (
curNode.left
) to the queue if it exists. - Update
result
with the current node’s value (curNode.val
).
- Poll the current node (
- While the queue is not empty:
- Return:
- After the loop,
result
will hold the value of the bottom-left node.
- After the loop,
Key Points
- By adding the right child before the left child, the BFS ensures that the last node encountered in the traversal will be the left-most node at the deepest level of the tree.
Complete Code
Here is the complete code with detailed comments:
package leetcode板块;
import java.util.ArrayDeque;
import java.util.Queue;
public class _513找树左下角的值_bfs层次最左 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
/**
* Finds the bottom-left value of a binary tree using BFS.
* @param root The root of the binary tree.
* @return The value of the bottom-left node.
*/
public int findBottomLeftValue(TreeNode root) {
int result = 0;
Queue<TreeNode> myQueue = new ArrayDeque<TreeNode>();
myQueue.offer(root);
while (!myQueue.isEmpty()) {
TreeNode curNode = myQueue.poll();
// Add right child first, then left child
if (curNode.right != null) {
myQueue.offer(curNode.right);
}
if (curNode.left != null) {
myQueue.offer(curNode.left);
}
// Update result with the current node's value
result = curNode.val;
}
return result;
}
}
Summary
- The BFS approach traverses the tree level by level from right to left.
- By adding the right child before the left child to the queue, the last node processed is the left-most node at the deepest level.
- The
result
variable stores the value of the bottom-left node, which is returned at the end of the traversal.