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)10
* @param {TreeNode} root13
var longestZigZag = function (root) {16
// Recursive left and right node and find the largest height17
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));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)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) {35
// Recursive to see which one is higher, zigzag to left or zigzag to right36
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));40
return isLeft === true ? left : right;