题目:
![](https://img.haomeiwen.com/i9044981/00ea26c13b73b4b5.png)
思路:
分几种情况:
1.如果root为空,直接返回false
2.如果root不为空:
2.1.左、右子树节点都为空,且根节点的值等于sum,直接返回true
2.2.左右子树节点任意为空或者都不为空,
则递归hasPathSum(root.left,sum-root.val)
&&hasPathSum(root.right,sum-root.val)
![](https://img.haomeiwen.com/i9044981/730218e30a24f5e7.png)
代码实现:
![](https://img.haomeiwen.com/i9044981/fb0a532760158c63.png)
题目:
思路:
分几种情况:
1.如果root为空,直接返回false
2.如果root不为空:
2.1.左、右子树节点都为空,且根节点的值等于sum,直接返回true
2.2.左右子树节点任意为空或者都不为空,
则递归hasPathSum(root.left,sum-root.val)
&&hasPathSum(root.right,sum-root.val)
本文标题:LeetCode112 路径之和
本文链接:https://www.haomeiwen.com/subject/bgmioctx.html
网友评论