LeetCode 112. Path Sum
2020-05-20 20:52:35 # leetcode

Problem

LeetCode 112. Path Sum

1. 题目简述

给出一棵二叉树和一个sum值,根节点为root,求从root节点到叶子节点是否存在一条路径其节点之和为sum。例如:

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.

2. 算法思路

DFS

很简单的DFS的思路,中序遍历的思路,记录从根节点到当前节点的和,到达根节点时做一次判断。

3. 解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null && sum == root.val) {
return true;
}

return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
}