-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathLongestZigZagPathInABinaryTree.java
59 lines (46 loc) · 1.27 KB
/
LongestZigZagPathInABinaryTree.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package Tree;
public class LongestZigZagPathInABinaryTree {
public static void main(String[] args) {
}
static int ans = 0;
public static int longestZigZag(TreeNode root) {
// it not has zigzag path in a binary tree
if (root == null || (root.left == null && root.right == null)) {
return 0;
}
solver(root.left, 1, "left");
solver(root.right, 1, "right");
return ans - 1;
}
private static void solver(TreeNode root, int temp, String dir) {
ans = Math.max(ans, temp);
if (root == null) {
return;
}
// left side
if (dir.equals("left")) {
solver(root.right, temp + 1, "right");
solver(root.left, 1, "left");
}
// right side
if (dir.equals("right")) {
solver(root.right, 1, "right");
solver(root.left, temp + 1, "left");
}
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
}