513. 找树左下角的值
https://leetcode.cn/problems/find-bottom-left-tree-value/description/
public int findBottomLeftValue(TreeNode root) {
int val = 0;
Deque<TreeNode> deque = new ArrayDeque<>();
deque.offer(root);
while (!deque.isEmpty()){
int len = deque.size();
for (int i = 0; i < len; i++) {
TreeNode node = deque.poll();
if (i == 0) val = node.val;
if (node.left != null) deque.offer(node.left);
if (node.right != null) deque.offer(node.right);
}
}
return val;
}
总结:层序遍历
112. 路径总和
https://leetcode.cn/problems/path-sum/description/
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) return false;
boolean sum = sum(root, targetSum);
return sum;
}
public boolean sum(TreeNode node,int sum){
if (node.left == null && node.right == null) {
return sum - node.val == 0; // 到达叶子节点时判断路径和是否等于目标和
}
boolean sumLeft = false;
boolean sumRight = false;
if (node.left != null) {
sumLeft = sum(node.left, sum - node.val);
}
if (node.right != null){
sumRight = sum(node.right, sum - node.val);
}
return sumLeft || sumRight;
}
总结:递归到叶子节点,判断是否合理
113. 路径总和 II
https://leetcode.cn/problems/path-sum-ii/description/
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
List<List<Integer>> resList = new ArrayList<>();
List<Integer> path = new ArrayList<>();
if (root == null) return resList;
pathSSum(root,targetSum,resList,path);
return resList;
}
public void pathSSum(TreeNode node,int targetSum,List<List<Integer>> resList,List<Integer> path){
if (node.left == null && node.right == null){
if (targetSum - node.val == 0){
path.add(node.val);
resList.add(new ArrayList<>(path));
path.remove(path.size() - 1); //回溯
}
return;
}
if (node.left != null){
path.add(node.val);
pathSSum(node.left,targetSum - node.val,resList,path);
path.remove(path.size() - 1); //回溯
}
if (node.right != null){
path.add(node.val);
pathSSum(node.right,targetSum - node.val,resList,path);
path.remove(path.size() - 1); //回溯
}
}
总结:带了点回溯
标签:node,第十八天,val,sum,路径,left,path,null,总和 From: https://www.cnblogs.com/jeasonGo/p/18091010