路径总和

此博客链接:https://www.cnblogs.com/ping2yingshi/p/14118349.html

路径总和

题目链接:https://leetcode-cn.com/problems/path-sum/

题目

给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

说明: 叶子节点是指没有子节点的节点。

示例: 
给定如下二叉树,以及目标和 sum = 22,

5
/
4 8
/ /
11 13 4
/
7 2 1
返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。

题解

思路:使用递归处理,先把递归的代码写出来,然后进行修改。对二叉树进行递归,然后判断到叶子节点的值是否等于给定的值,如果有相等的值,则返回true。如果没有,则遍历右子树或者左子树,直到遍历完。

代码

class Solution {
    boolean panduan;
    public boolean hasPathSum(TreeNode root, int sum) {
             Ispanduan(root,sum);
            return panduan;
    }
    public void Ispanduan(TreeNode root,int count){
        if(root==null)
                return ;
        count=count-root.val;
        if(root.left==null&&root.right==null){
            if(count==0)
                panduan=true;
                count=count+root.val;
            return ;
        }
        Ispanduan(root.left,count);
        Ispanduan(root.right,count);
        count=count+root.val;
    }
}

结果

出来混总是要还的
原文地址:https://www.cnblogs.com/ping2yingshi/p/14118349.html