C++
Java
Python
Python3
C
C#
JavaScript
Ruby
Swift
Go
Scala
Kotlin
Rust
PHP
TypeScript
Racket
Erlang
Elixir
Dart
monokai
ambiance
chaos
chrome
cloud9_day
cloud9_night
cloud9_night_low_color
clouds
clouds_midnight
cobalt
crimson_editor
dawn
dracula
dreamweaver
eclipse
github
github_dark
gob
gruvbox
gruvbox_dark_hard
gruvbox_light_hard
idle_fingers
iplastic
katzenmilch
kr_theme
kuroir
merbivore
merbivore_soft
mono_industrial
nord_dark
one_dark
pastel_on_dark
solarized_dark
solarized_light
sqlserver
terminal
textmate
tomorrow
tomorrow_night
tomorrow_night_blue
tomorrow_night_bright
tomorrow_night_eighties
twilight
vibrant_ink
xcode
上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int target) {
}
};
运行代码
提交
python3 解法, 执行用时: 44 ms, 内存消耗: 16.6 MB, 提交时间: 2022-11-14 10:32:25
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]:
ret = list()
path = list()
def dfs(root: TreeNode, targetSum: int):
if not root:
return
path.append(root.val)
targetSum -= root.val
if not root.left and not root.right and targetSum == 0:
ret.append(path[:])
dfs(root.left, targetSum)
dfs(root.right, targetSum)
path.pop()
dfs(root, targetSum)
return ret
golang 解法, 执行用时: 8 ms, 内存消耗: 4.4 MB, 提交时间: 2022-11-14 10:31:59
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func pathSum(root *TreeNode, targetSum int) (ans [][]int) {
path := []int{}
var dfs func(*TreeNode, int)
dfs = func(node *TreeNode, left int) {
if node == nil {
return
}
left -= node.Val
path = append(path, node.Val)
defer func() { path = path[:len(path)-1] }()
if node.Left == nil && node.Right == nil && left == 0 {
ans = append(ans, append([]int(nil), path...))
return
}
dfs(node.Left, left)
dfs(node.Right, left)
}
dfs(root, targetSum)
return
}