LeetCode 112—路径总和
程序员文章站
2022-05-20 11:17:58
...
递归:
public boolean hasPathSum(TreeNode root, int sum) {
if(root==null) return false;
if(root.left==null&&root.right==null&&sum==0) return true;
return hasPathSum(root.left, sum-root.val)||hasPathSum(root.right, sum-root.val);
}
迭代:
public boolean hasPathSum(TreeNode root, int sum) {
if (root==null) return false;
Stack<TreeNode> stack=new Stack<TreeNode>();
stack.push(root);
while (!stack.empty()) {
TreeNode t = stack.pop();
if (t.left==null && t.right==null) {
if (t.val == sum) return true;
}
if (t.right!=null) {
t.right.val += t.val;
stack.push(t.right);
}
if (t.left!=null) {
t.left.val += t.val;
stack.push(t.left);
}
}
return false;
}
上一篇: 晒晒爸妈让人冒汗的搞笑事儿
下一篇: 现在的孩子真够雷人的。
推荐阅读
-
[leetcode]不同路径三连击~
-
【leetcode 简单】 第一百五十题 两个列表的最小索引总和
-
荐 LeetCode 120. 三角形最小路径和 | Python
-
【每日一道算法题】Leetcode之longest-increasing-path-in-a-matrix矩阵中的最长递增路径问题 Java dfs+记忆化
-
#leetcode刷题之路40-组合总和 II
-
荐 LeetCode 112. 路径总和 | Python
-
动态规划_leetcode.64.最小路径和
-
LeetCode 63. 不同路径 II
-
[leetcode]63. 不同路径 II
-
LeetCode——63.不同路径 II