Skip to content

Commit 757f363

Browse files
committed
Add solution #1372
1 parent b01b962 commit 757f363

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,7 @@
426426
1365|[How Many Numbers Are Smaller Than the Current Number](./1365-how-many-numbers-are-smaller-than-the-current-number.js)|Easy|
427427
1366|[Rank Teams by Votes](./1366-rank-teams-by-votes.js)|Medium|
428428
1368|[Minimum Cost to Make at Least One Valid Path in a Grid](./1368-minimum-cost-to-make-at-least-one-valid-path-in-a-grid.js)|Hard|
429+
1372|[Longest ZigZag Path in a Binary Tree](./1372-longest-zigzag-path-in-a-binary-tree.js)|Medium|
429430
1374|[Generate a String With Characters That Have Odd Counts](./1374-generate-a-string-with-characters-that-have-odd-counts.js)|Easy|
430431
1380|[Lucky Numbers in a Matrix](./1380-lucky-numbers-in-a-matrix.js)|Easy|
431432
1389|[Create Target Array in the Given Order](./1389-create-target-array-in-the-given-order.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* 1372. Longest ZigZag Path in a Binary Tree
3+
* https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/
4+
* Difficulty: Medium
5+
*
6+
* You are given the root of a binary tree.
7+
*
8+
* A ZigZag path for a binary tree is defined as follow:
9+
* - Choose any node in the binary tree and a direction (right or left).
10+
* - If the current direction is right, move to the right child of the current node;
11+
* otherwise, move to the left child.
12+
* - Change the direction from right to left or from left to right.
13+
* - Repeat the second and third steps until you can't move in the tree.
14+
*
15+
* Zigzag length is defined as the number of nodes visited - 1. (A single node has a
16+
* length of 0).
17+
*
18+
* Return the longest ZigZag path contained in that tree.
19+
*/
20+
21+
/**
22+
* Definition for a binary tree node.
23+
* function TreeNode(val, left, right) {
24+
* this.val = (val===undefined ? 0 : val)
25+
* this.left = (left===undefined ? null : left)
26+
* this.right = (right===undefined ? null : right)
27+
* }
28+
*/
29+
/**
30+
* @param {TreeNode} root
31+
* @return {number}
32+
*/
33+
var longestZigZag = function(root) {
34+
let result = 0;
35+
36+
dfs(root, true, 0);
37+
dfs(root, false, 0);
38+
39+
return result;
40+
41+
function dfs(node, isLeft, total) {
42+
if (!node) return;
43+
result = Math.max(result, total);
44+
dfs(node.left, true, isLeft ? 1 : total + 1);
45+
dfs(node.right, false, isLeft ? total + 1 : 1);
46+
}
47+
};

0 commit comments

Comments
 (0)