解题思路:采用递归的方式。若root不为空,且存在左右子节点,则继续向下递归;否则root为空,返回false;root没有左右子节点且root值等于sum,返回true。疑问:我的解题思路和别人的一样,但是实现没有别人的简洁,所以运行超时?
别人的代码实现:
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
public boolean hasPathSum (TreeNode root, int sum) {
if(root == null){
return false;
}
if(root.left == null && root.right == null){
return (sum - root.val == 0);
}
return hasPathSum(root.left,sum - root.val) || hasPathSum(root.right,sum - root.val);
}
}我的代码实现:
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
public boolean hasPathSum (TreeNode root, int sum) {
// write code here
int flag=0;
while(root!=null&&root.val<=sum){
if(root.left!=null){
if(hasPathSum(root.left,sum-root.val)){
return true;
}
}
if(flag==0&&root.right!=null){
if(hasPathSum(root.right,sum-root.val)){
return true;
}
}
if(root.left==null&&root.right==null&&root.val==sum){
return true;
}
}
return false;
}
}
京公网安备 11010502036488号