import java.util.Deque;
import java.util.LinkedList;
/**
* @author xnl
* @Description:
* @date: 2022/6/22 21:35
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
TreeNode treeNode = new TreeNode(2, new TreeNode(1), new TreeNode(3));
System.out.println(solution.findBottomLeftValue(treeNode));
}
int n = 0;
int res = 0;
public int findBottomLeftValue(TreeNode root) {
dfs(root, 0);
return res;
}
/**
* 深度优先遍历
* @param root
* @param height
*/
private void dfs(TreeNode root, int height){
if (root == null){
return;
}
height++;
dfs(root.left, height);
dfs(root.right, height);
if (height > n){
n = height;
res = root.val;
}
}
/**
* 广度优先遍历
* @param root
*
*/
private int findBottomLeftValue2(TreeNode root){
int res = 0;
Deque<TreeNode> stack = new LinkedList<>();
stack.offer(root);
while (!stack.isEmpty()){
TreeNode temp = stack.poll();
if (temp.right != null){
stack.offer(temp.right);
}
if (temp.left != null){
stack.offer(temp.left);
}
res = temp.val;
}
return res;
}
}
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;
}
}
力扣:513. 找树左下角的值
于 2022-06-22 22:05:51 首次发布
该博客主要展示了如何使用Java进行深度优先搜索(DFS)和广度优先搜索(BFS)来找到二叉树的底部左节点。代码中定义了一个Solution类,包含两个方法:findBottomLeftValue和findBottomLeftValue2,分别使用DFS和BFS策略。通过这两个方法,可以找到树的最后一层最左边的节点的值。
315

被折叠的 条评论
为什么被折叠?



