7月7日签到题,题目如下:
给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22,5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
本题较为简单,前序遍历所有叶子节点,直到找出解或者遍历结束即可。
复杂度分析直接引用官方题解,我至今不明白递归的空间复杂度为什么是O(logN),望路过的大佬可以指教。
以下为自己提交的代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public bool HasPathSum(TreeNode root, int sum) {
if (root == null)
{
return false;
}
return CheckNode(root,sum, 0);
}
private bool CheckNode(TreeNode node,int sum,int nowSum)
{
int nextSum = nowSum + node.val;
if (node.left == null && node.right == null)
{
return nextSum == sum;
}
else
{
bool left = node.left != null ? CheckNode(node.left,sum,nextSum) : false;
if (left)
{
return left;
}
else
{
return node.right != null ? CheckNode(node.right,sum,nextSum) : false;
}
}
}
}