FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
JavaArithmetic/src/LeetCode/LeetCode112.java at master · Edwardlinge/JavaArithmetic · GitHub
Edwardlinge
JavaArithmetic
Repository navigation
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
JavaArithmetic
/
src
/
LeetCode
/
LeetCode112.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
36 lines (26 loc) · 1 KB
Breadcrumbs
JavaArithmetic
/
src
/
LeetCode
/
LeetCode112.java
Copy path
File metadata and controls
36 lines (26 loc) · 1 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
28
29
30
31
32
33
34
35
36
package
LeetCode
;
public
class
LeetCode112
{
/// 112. Path Sum
/// https://leetcode.com/problems/path-sum/description/
/// 时间复杂度: O(n), n为树的节点个数
/// 空间复杂度: O(h), h为树的高度
// Definition for a binary tree node.
public
class
TreeNode
{
int
val
;
TreeNode
left
;
TreeNode
right
;
TreeNode
(
int
x
) {
val
=
x
; }
}
// 从根节点到叶子节点,有没有路径为sum
// 确定了根节点是必须要的,那我们就可以分解成
// 根节点下的子节点,有没有路径为sum - root.val!!!(其实就是子问题)
public
boolean
hasPathSum
(
TreeNode
root
,
int
sum
) {
if
(
root
==
null
)
return
false
;
// 根节点到叶子节点,所以递归的出口是叶子节点
if
(
root
.
left
==
null
&&
root
.
right
==
null
)
return
sum
==
root
.
val
;
return
hasPathSum
(
root
.
left
,
sum
-
root
.
val
)
||
hasPathSum
(
root
.
right
,
sum
-
root
.
val
);
}
}
Back
|
FazBrowse Home
|
New Git URL