513. 找树左下角的值
/**
* 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 null;
// }
Queue<TreeNode> queue = new LinkedList<>();
int result = 0;
queue.add(root);
while(!queue.isEmpty()){
int size = queue.size();
for(int i = 0; i< size; i++){
TreeNode node = queue.poll();
if(node.left != null){
queue.add(node.left);
}
if(node.right != null){
queue.add(node.right);
}
// 记录最后一行的最左边元素
if(i == 0){
result = node.val;
}
}
}
return result;
}
}
112. 路径总和
/**
* 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 boolean hasPathSum(TreeNode root, int targetSum) {
if(root == null){
return false;
}
if(root.left == null && root.right == null){
return root.val == targetSum;
}
return hasPathSum(root.left,targetSum - root.val) || hasPathSum(root.right,targetSum-root.val);
}
}
113. 路径总和ii
/**
* 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 {
// 结果列表 用于保存所有满足条件的路径
private List<List<Integer>> result = new ArrayList<>();
// 路径列表 用于保存当前路径
private List<Integer> path = new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
// 从根节点开始深度优先搜索
dfs(root, targetSum);
return result;
}
private void dfs(TreeNode root, int sum){
// 如果当前节点为空 直接返回
if(root == null){
return;
}
// 将当前节点的值添加到路径中
path.add(root.val);
// 从 sum 中减去当前节点的值
sum -= root.val;
// 如果当前节点是叶子节点 并且 sum 等于0 说明我们找到了一条满足条件的路径
if(root.left == null && root.right == null && sum == 0){
// 将当前路径添加到结果列表中
// 注意需要复制一份 path 否则后续对 path的修改会影响已经添加到结果列表的路径
result.add(new ArrayList<>(path));
} else {
// 继续搜索左子树和右子树
dfs(root.left, sum);
dfs(root.right,sum);
}
// 回溯 移除路径中的当前节点 以便 用于搜索其他路径
path.remove(path.size() -1);
}
}