|
| 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