Longest ZigZag Path in a Binary Tree LeetCode solution in JavaScript

1
/** https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/
2
* Definition for a binary tree node.
3
* function TreeNode(val, left, right) {
4
* this.val = (val===undefined ? 0 : val)
5
* this.left = (left===undefined ? null : left)
6
* this.right = (right===undefined ? null : right)
7
* }
8
*/
9
/**
10
* @param {TreeNode} root
11
* @return {number}
12
*/
13
var longestZigZag = function (root) {
14
this.out = 0;
15

16
// Recursive left and right node and find the largest height
17
let left = dfs(root.left, false) + 1;
18
let right = dfs(root.right, true) + 1;
19
this.out = Math.max(this.out, Math.max(left, right));
20

21
return this.out;
22
};
23

24
var dfs = function (node, isLeft) {
25
// Node is null, we return -1 because the caller will add 1, so result in 0 (no node visited)
26
if (node == null) {
27
return -1;
28
}
29

30
// No left or right node, we return 0 because the caller will add 1, so result in 1 (visited 1 node - this one)
31
if (node.left == null && node.right == null) {
32
return 0;
33
}
34

35
// Recursive to see which one is higher, zigzag to left or zigzag to right
36
let left = dfs(node.left, false) + 1;
37
let right = dfs(node.right, true) + 1;
38
this.out = Math.max(this.out, Math.max(left, right));
39

40
return isLeft === true ? left : right;
41
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0