112|112 Path Sum
title: Path Sum
tags:
- path-sum
- No.112
- simple
- tree
- recursive
Description
【112|112 Path Sum】Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22
,
5
/ \
48
// \
11134
/\\
721
return true, as there exist a root-to-leaf path
5->4->11->2
which sum is 22.Corner Cases
- empty tree
/**
* Definition for a binary tree node.
* public class TreeNode {
*int val;
*TreeNode left;
*TreeNode right;
*TreeNode(int x) { val = x;
}
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {return false;
}
return f(root, sum);
}private boolean f(TreeNode x, int s) {
if (x.left == null && x.right == null && x.val == s) {return true;
}boolean fl = false;
boolean fr = false;
if (x.left!= null) {fl = f(x.left,s - x.val);
}
if (x.right != null) {fr = f(x.right, s - x.val);
}
return fl || fr;
}
}
推荐阅读
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- Python(pathlib模块)
- Realm
- 二叉树路径节点关键值和等于目标值(LeetCode--112&LeetCode--113)
- 2018-02-08|2018-02-08 P101-P112学习心得
- 熠煊妈妈亲子日记第112天
- 古有商鞅变法,今有Pathways攻占头马
- C#|C# 文件路径操作
- mac升级之(xcrun:|mac升级之:xcrun: error: invalid active developer path, missing xcrun)
- 中原焦点团队?焦点解决网初18中20张红勋坚持分享第295天约练第112次2020年12月3日读书打卡第195天