我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/path-sum/description/
题目描述:
知识点:递归、树的深度优先遍历
思路一:递归
递归终止条件:
(1)如果root为null,返回false。
(2)如果root的值为sum且root的左右孩子均为null,返回true。
递归过程:
sum减去root的值并递归判断其左子树或右子树是否有等于sum的路径。
时间复杂度和空间复杂度均是O(h),其中h为树的高度。
JAVA代码:
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) {
return false;
}
if(root.val == sum && root.left == null && root.right == null) {
return true;
}
sum -= root.val;
return hasPathSum(root.left, sum) || hasPathSum(root.right, sum);
}
}
LeetCode解题报告:
思路二:深度优先遍历
本质上和思路一是一致的。
时间复杂度和空间复杂度均是O(h),其中h为树的高度。
JAVA代码:
public class Solution {
boolean flag = false;
public boolean hasPathSum(TreeNode root, int sum) {
if(null == root){
return flag;
}
dfs(root, sum);
return flag;
}
private void dfs(TreeNode root, int sum) {
if(null == root.left && null == root.right){
sum -= root.val;
if(sum == 0){
flag = true;
}
return;
}
if(null != root.left){
dfs(root.left, sum - root.val);
}
if(null != root.right){
dfs(root.right, sum - root.val);
}
}
}
LeetCode解题报告: