Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit5e40347

Browse files
authored
Create 0515-find-largest-value-in-each-tree-row.kt
1 parente89cfed commit5e40347

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// bfs
2+
classSolution {
3+
funlargestValues(root:TreeNode?):List<Int> {
4+
val res= mutableListOf<Int>()
5+
root?:return res
6+
7+
with (LinkedList<TreeNode?>()) {
8+
addLast(root)
9+
10+
while (isNotEmpty()) {
11+
var levelMax= peekLast()!!.`val`
12+
13+
repeat (size) {
14+
val cur= removeFirst()
15+
levelMax= maxOf(levelMax, cur!!.`val`)
16+
cur?.left?.let { addLast(it) }
17+
cur?.right?.let { addLast(it) }
18+
}
19+
20+
res.add(levelMax)
21+
}
22+
}
23+
24+
return res
25+
}
26+
}
27+
28+
// dfs
29+
classSolution {
30+
funlargestValues(root:TreeNode?):List<Int> {
31+
root?:return listOf<Int>()
32+
33+
val maxes=HashMap<Int,Int>()
34+
35+
fundfs(cur:TreeNode?,level:Int) {
36+
cur?:return
37+
38+
maxes[level]= maxOf(
39+
cur?.value?:Integer.MIN_VALUE,
40+
maxes.getOrDefault(level,Integer.MIN_VALUE)
41+
)
42+
43+
dfs(cur?.left, level+1)
44+
dfs(cur?.right, level+1)
45+
}
46+
47+
dfs(root,0)
48+
return maxes.values.toList()
49+
}
50+
51+
valTreeNode.value
52+
get()=this.`val`
53+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp