提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
二叉树的递归分为「遍历」和「分解问题」两种思维模式,这道题需要用到「遍历」的思维模式
一、力扣1602. 找到二叉树中最近的右侧节点
/**
* 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 dif = Integer.MAX_VALUE;
TreeNode res = null;
int high = -1;
int flag = -1;
public TreeNode findNearestRightNode(TreeNode root, TreeNode u) {
fun(root, u, 1,1);
return res;
}
public void fun(TreeNode root, TreeNode u, int index, int depth){
if(root == null){
return;
}
if(root == u){
high = depth;
flag = index;
}else if(high == depth){
if((index - flag) < dif){
res = root;
dif = index - flag;
}
}
fun(root.left , u, index * 2, depth + 1);
fun(root.right, u, index *2 + 1, depth + 1);
}
}
二、力扣437. 路径总和 III
/**
* 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 {
Map<Long,Integer> preSumPath = new HashMap<>();
int res = 0;
long targetSum , pathSum ;
public int pathSum(TreeNode root, int targetSum) {
if(root == null){
return 0;
}
this.targetSum = targetSum;
this.pathSum = 0;
preSumPath.put(0L,1);
fun(root);
return res;
}
public void fun(TreeNode root){
if(root == null){
return;
}
pathSum += root.val;
res += preSumPath.getOrDefault(pathSum - targetSum,0);
preSumPath.put(pathSum, preSumPath.getOrDefault(pathSum,0)+1);
fun(root.left);
fun(root.right);
preSumPath.put(pathSum,preSumPath.getOrDefault(pathSum,0)-1);
pathSum -= root.val;
}
}
三、力扣560. 和为 K 的子数组
class Solution {
public int subarraySum(int[] nums, int k) {
int[] preSum = new int[nums.length+1];
for(int i = 0; i < nums.length; i ++){
preSum[i+1] = nums[i] + preSum[i];
}
int count = 0;
for(int low = 0; low < preSum.length - 1; low ++){
for(int high = low; high < preSum.length-1; high ++){
if(preSum[high + 1] - preSum[low] == k){
count ++;
}
}
}
return count;
}
}
文章介绍了如何使用递归遍历方法解决力扣(LeetCode)中的三个二叉树相关问题:1602找最近右侧节点、437路径总和III和560和为K的子数组,展示了在遍历过程中计算和更新状态的解题思路。
740

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



