binary-tree - 为 Leetcode 112 寻找正确的递归算法
问题描述
我正在解决 Leet Code 问题112。路径总和:
给定
root
一个二叉树和一个整数targetSum
,true
如果树有一个从根到叶的路径,使得沿路径的所有值相加等于 ,则返回targetSum
。叶是没有子节点的节点。
我下面的代码试图解决它,但显然它不正确,因为我不断遇到失败的测试用例。
/**
* 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.left==null&&root.right==null&&targetSum-root.val ==0)
return true;
else{
if(root.right!= null){
hasPathSum(root.right, targetSum-root.val);
}
if(root.left!=null) {
hasPathSum(root.left, targetSum-root.val);
}
} return false;
}
}
这段代码有什么问题?
解决方案
您没有使用您进行的递归调用返回的值。以冗长的方式,您可以按如下方式修复该部分代码:
boolean result = false;
if (root.right != null) {
result = hasPathSum(root.right, targetSum - root.val);
}
if (!result && root.left != null) {
result = hasPathSum(root.left, targetSum - root.val);
}
return result;
当您为此使用更多逻辑运算符时,它会更紧凑:
return root.right != null && hasPathSum(root.right, targetSum - root.val)
|| root.left != null && hasPathSum(root.left, targetSum - root.val);
Leet Code 挑战中没有明确说明,但是当在空树上调用这个函数时,它应该返回false
。所以你应该预见到 is 的root
情况null
。
完整的解决方案可能如下所示:
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
return root != null &&
( root.left == null && root.right == null && targetSum == root.val
|| root.right != null && hasPathSum(root.right, targetSum - root.val)
|| root.left != null && hasPathSum(root.left, targetSum - root.val)
);
}
}
推荐阅读
- reactjs - 在 React 组件中排序
- php - 如何匹配“有”,而不是“有”
- javascript - 在 Angular 中访问当前 DOM 节点的子节点
- winapi - winAPI GetAdaptersAddresses 不可打印的友好名称
- python - 如何使用外部文件存在/内容控制 python 程序行为?
- javascript - React Native TouchableOpacity 不适用于绝对位置
- gatsby - 纱线:在 gatsby 部署到 netlify 后找不到命令
- c++ - win32/C++ 在资源中嵌入文本文件
- c# - 如何将 WPF 中的自动设置参数与 MVVM 绑定
- c++ - 使用“friend”关键字重载 C++ 运算符