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

Appearance settings

Commit a9c47ca

Browse filesBrowse files
author
night
committed
num with island Tree version
1 parent 122ab23 commit a9c47ca
Copy full SHA for a9c47ca

File tree

1 file changed

+33
-0
lines changed
Filter options

1 file changed

+33
-0
lines changed
+33Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.blankj.google
2+
3+
import com.blankj.ext.print
4+
import com.blankj.structure.TreeNode
5+
import kotlin.math.max
6+
7+
class CountIslandWithTree {
8+
fun countIslands(root: TreeNode?): Int {
9+
var count = 0
10+
fun dfs(node: TreeNode?): Int {
11+
if (node == null) return 0
12+
val left = dfs(node.left)
13+
val right = dfs(node.right)
14+
// 如果当前节点为 1 且左右子节点都为 0,则表示找到一个新的岛屿
15+
if (node.`val` == 1 && left == 0 && right == 0) {
16+
count++
17+
}
18+
if (node.`val` == 1 && left == 1 && right == 1) {
19+
count--
20+
}
21+
// 返回当前节点及其左右子节点组成的岛屿数量
22+
return node.`val`
23+
}
24+
dfs(root)
25+
return count
26+
}
27+
}
28+
29+
fun main() {
30+
CountIslandWithTree().countIslands(TreeNode.createTestData("[1,0,0,1,1,1]")).print()
31+
CountIslandWithTree().countIslands(TreeNode.createTestData("[1,0,1,1,1,1]")).print()
32+
CountIslandWithTree().countIslands(TreeNode.createTestData("[1,1,1,1,1,1]")).print()
33+
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.