File tree Expand file tree Collapse file tree 3 files changed +54
-0
lines changed Expand file tree Collapse file tree 3 files changed +54
-0
lines changed Original file line number Diff line number Diff line change 1+ let binaryTreePaths = function ( root ) {
2+ let res = [ ]
3+ let dfs = ( node , path = "" ) => {
4+ if ( ! node ) {
5+ return
6+ }
7+
8+ let newPath = path ? `${ path } ->${ node . val } ` : `${ node . val } `
9+ if ( ! node . left && ! node . right ) {
10+ res . push ( newPath )
11+ }
12+
13+ dfs ( node . left , newPath )
14+ dfs ( node . right , newPath )
15+ }
16+ dfs ( root )
17+ return res
18+ }
Original file line number Diff line number Diff line change 1+ let sumOfLeftLeaves = function ( root ) {
2+ let sum = 0
3+
4+ let dfs = ( node ) => {
5+ if ( ! node ) return
6+
7+ if ( isLeaf ( node . left ) ) {
8+ sum += node . left . val
9+ }
10+
11+ dfs ( node . left )
12+ dfs ( node . right )
13+ }
14+
15+ dfs ( root )
16+
17+ return sum
18+ }
19+
20+ function isLeaf ( node ) {
21+ return ! ! node && ! node . left && ! node . right
22+ }
Original file line number Diff line number Diff line change 1+ let hasPathSum = function ( root , sum ) {
2+ if ( ! root ) {
3+ return false
4+ }
5+ // 叶子节点 判断当前的值是否等于 sum 即可
6+ if ( ! root . left && ! root . right ) {
7+ return root . val === sum
8+ }
9+
10+ return (
11+ hasPathSum ( root . left , sum - root . val ) ||
12+ hasPathSum ( root . right , sum - root . val )
13+ )
14+ }
You can’t perform that action at this time.
0 commit comments