题解 | #二叉树中和为某一值的路径(一)#
二叉树中和为某一值的路径(一)
https://www.nowcoder.com/practice/508378c0823c423baa723ce448cbfd0c
using System;
using System.Collections.Generic;
/*
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode (int x)
{
val = x;
}
}
*/
class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
public bool hasPathSum (TreeNode root, int sum) {
// write code here
//前序遍历,递归。从根节点到叶子节点的一条路,看成根节点值+子树值,子树又是根节点加子树,且此时的sum=sum-上一个根节点.val
//递归结束条件:根节点空或此时根节点为叶子节点且sum一致
if(root==null)
return false;
if(root.right==null&&root.left==null&&root.val==sum)
return true;
return (hasPathSum(root.left,sum-root.val) || hasPathSum(root.right,sum-root.val));
}
}
美的集团公司福利 798人发布