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

Commit 98d1347

Browse files
1372. Longest ZigZag Path in a Binary Tree
1 parent 7d3dff0 commit 98d1347

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

‎1372.LongestZigZagPathinaBinaryTree.kt

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* Example:
3+
* var ti = TreeNode(5)
4+
* var v = ti.`val`
5+
* Definition for a binary tree node.
6+
* class TreeNode(var `val`: Int) {
7+
* var left: TreeNode? = null
8+
* var right: TreeNode? = null
9+
* }
10+
*/
11+
//https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/description
12+
class Solution {
13+
var longestPath = 0
14+
fun longestZigZag(root: TreeNode?): Int {
15+
dfs(root, 0, 0)
16+
return longestPath
17+
}
18+
19+
fun dfs(node: TreeNode?, leftLength: Int, rightLength: Int){
20+
if (node == null) {
21+
return
22+
}
23+
longestPath = maxOf(longestPath, maxOf(leftLength, rightLength))
24+
dfs(node.left, rightLength + 1, 0)
25+
dfs(node.right, 0, leftLength + 1)
26+
}
27+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /