博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
9.path Sum III(路径和 III)
阅读量:4632 次
发布时间:2019-06-09

本文共 1484 字,大约阅读时间需要 4 分钟。

Level:

  Easy

题目描述:

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

Example:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8      10     /  \    5   -3   / \    \  3   2   11 / \   \3  -2   1Return 3. The paths that sum to 8 are:1.  5 -> 32.  5 -> 2 -> 13. -3 -> 11

思路分析:

  由于题目中所说的路径,不局限于从根到叶子节点,任何一个节点都可以作为路径的开始节点和终止节点,所以我们以根节点作为开始节点,查找和为sum的路径数,然后分别以根的左孩子和右孩子为起始节点去查找和为sum的路径数,依次递归向下推导,得到最终的结果。

代码:

/**public class TreeNode{    int vla;    TreeNode left;    TreeNode right;    public TreeNode(int val){        this.val=val;    }}*/public class Soulution{    public int pathSum(TreeNode root,int sum){        if(root==null)            return 0;        int res=0;        res=pathCheck(root,sum);        res=res+pathSum(root.left,sum);        res=res+pathSum(root.right,sum);        return res;    }    public int pathCheck(TreeNode root,int sum){        if(root==null)            return 0;        int count=0;        if(sum==root.val)//当sum等于root.val时证明存在一条路径和为sum            count++;        count=count+pathCheck(root.left,sum-root.val);        count=count+pathCheck(root.right,sum-root.val);        return count;    }}

转载于:https://www.cnblogs.com/yjxyy/p/10703197.html

你可能感兴趣的文章
单相计量芯片RN8209D使用经验分享(转)
查看>>
灵活性是原则性基础上的灵活
查看>>
python 添加进度条
查看>>
恢复Opera11.50地址栏的下拉列表按钮
查看>>
EBS上用过的一些接口表整理信息
查看>>
ldconfig
查看>>
操作系统简介
查看>>
查看Linux系统中某目录的大小
查看>>
Git远程仓库地址变更
查看>>
PAT_B_1027 打印沙漏
查看>>
POJ-1185 炮兵阵地 动态规划+状态压缩
查看>>
NYOJ 366 D的小L
查看>>
PYTHON 写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者...
查看>>
Docker 初识
查看>>
【12.16】VC++调用Word OLE进行自动化生成报表
查看>>
用Maven创建第一个web项目
查看>>
php中的抽象类(abstract class)和接口(interface)
查看>>
linux安装ActiveMQ
查看>>
面向对象与软件工程---团队作业1
查看>>
认识一下Kotlin语言,Android平台的Swift
查看>>