LeetCode之17. Letter Combinations of a Phone Number

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \      \
7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

自己的代码:

Runtime: 0 ms, faster than 100.00% of Java online submissions for Path Sum.

Memory Usage: 38.6 MB, less than 62.51% of Java online submissions for Path Sum.

class Solution {
    public static boolean hasPathSum(TreeNode root, int sum) {
		if(root == null)  return false;
		boolean flag = false;
		
		flag = hasPathSumHelper(root,sum,0);
		
		return flag;
	}

	public static boolean hasPathSumHelper(TreeNode root, int sum,int curSum) {
		curSum += root.val; // 这句一定要写在最前面
		
		// if(curSum > sum) return false; 只有节点全是非负值时,才可使用这句来提速
        // if(curSum == sum) return true; 这可能导致还没走到了叶子节点就返回了

		if(curSum == sum && root.left == null && root.right == null) return true;
		
		boolean flag = false;
		
        // 指针的非空验证非常重要
		if(root.left != null) {
			flag = hasPathSumHelper(root.left,sum,curSum);
		}
		if(!flag && root.right != null) {
			flag = hasPathSumHelper(root.right,sum,curSum);
		}
		
		return flag;
	}
}

猜你喜欢

转载自blog.csdn.net/iNiBuBian/article/details/88266016