题目链接:https://leetcode.cn/problems/find-bottom-left-tree-value/
方法一 迭代
1 方法思想
2 代码实现
/**
* Definition for a binary tree node.
* 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;
* }
* }
*/
class Solution {
int maxDepth = -1;
int result = 0;
public int findBottomLeftValue(TreeNode root) {
if (root == null) return -1;
result = root.val;
findLeft(root, 0);
return result;
}
public void findLeft(TreeNode node, int depth) {
if (depth > maxDepth && node.right == null && node.left == null) {
maxDepth = depth;
result = node.val;
}
if (node.left != null) findLeft(node.left, depth + 1);
if (node.right != null) findLeft(node.right, depth + 1);
}
}
3 复杂度分析
时间复杂度:
空间复杂度:
4 涉及到知识点
5 总结
方法一 递归
1 方法思想
2 代码实现
/**
* Definition for a binary tree node.
* 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;
* }
* }
*/
class Solution {
public int findBottomLeftValue(TreeNode root) {
if (root == null) return -1;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int ans = 0;
while (!queue.isEmpty()) {
TreeNode top = queue.peek();
int size = queue.size();
ans = top.val;
while (size-- > 0) {
top = queue.poll();
if (top.left != null) {
queue.add(top.left);
}
if (top.right != null) {
queue.add(top.right);
}
}
}
return ans;
}
}
3 复杂度分析
时间复杂度:
空间复杂度: