-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem_1372.java
More file actions
40 lines (40 loc) · 1.5 KB
/
Copy pathproblem_1372.java
File metadata and controls
40 lines (40 loc) · 1.5 KB
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
/*
1372. Longest ZigZag Path in a Binary Tree
You are given the root of a binary tree.
A ZigZag path for a binary tree is defined as follow:
Choose any node in the binary tree and a direction (right or left).
If the current direction is right, move to the right child of the current node; otherwise, move to the left child.
Change the direction from right to left or from left to right.
Repeat the second and third steps until you can't move in the tree.
Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).
Return the longest ZigZag path contained in that tree. */
class Solution {
public int longestZigZag(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
int max = 0;
while(!stack.isEmpty()){
TreeNode node = stack.pop();
if(node == null) continue;
int left = zigzag_left(node);
int right = zigzag_right(node);
int bigger = left>right?left:right;
max = max>bigger?max:bigger;
if(node.right != null) stack.push(node.right);
if(node.left != null) stack.push(node.left);
}
return max;
}
public int zigzag_left(TreeNode node){
if(node.left != null){
return 1+zigzag_right(node.left);
}
return 0;
}
public int zigzag_right(TreeNode node){
if(node.right != null){
return 1+zigzag_left(node.right);
}
return 0;
}
}