题解 | #二叉树中和为某一值的路径(一)#
二叉树中和为某一值的路径(一)
http://www.nowcoder.com/practice/508378c0823c423baa723ce448cbfd0c
/*
* function TreeNode(x) {
* this.val = x;
* this.left = null;
* this.right = null;
* }
*/
/**
*
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
function hasPathSum( root , sum ) {
// 当root为空时,直接退出
if(root == null){
return false
}
return process(root, sum)
}
function process(root, sum){
// 遍历到空节点时,就说明没有找到
if(root == null){
return false
}
// 遍历到叶子节点
if(root.left == null && root.right == null){
return sum === root.val
}
// sum - 此节点的值
sum -= root.val
// 往下遍历左右节点,只要一个满足条件,就说明找到了
return process(root.right, sum) || process(root.left, sum)
}
module.exports = {
hasPathSum : hasPathSum
};
