Open songyy5517 opened 5 months ago
Approach: DFS with a Boolean variable
DFS(TreeNode root, int path_len, boolean right)
: Search the entire tree with DFS:
Complexity Analysis
/**
* Definition for a binary tree node.
* 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;
* }
* }
*/
class Solution {
int max_len = 0;
public int longestZigZag(TreeNode root) {
// Intuition: DFS
// 1. Exception Handling
if (root == null)
return 0;
dfs(root.left, 1, false);
dfs(root.right, 1, true);
return max_len;
}
// right: whether the current node is a right son of its father node
void dfs(TreeNode root, int path_len, boolean right){
if (root == null)
return ;
max_len = Math.max(max_len, path_len);
if (right){
dfs(root.left, path_len + 1, false);
dfs(root.right, 1, true);
}
else {
dfs(root.left, 1, false);
dfs(root.right, path_len + 1, true);
}
}
}
2024/6/4
You are given the root of a binary tree. A ZigZag path for a binary tree is defined as follow:
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.
Example 1:
Example 2:
Example 3:
Intuition The problem is to find the longest ZigZag path which includes the nodes whose direction is different from its father and son nodes. So a simple idea is searching the entire tree with DFS. The key here is to determine whether a path is a ZigZag path. To achieve this, we define an additional boolean variable in the DFS method to indicate whether the current node is the right node of its father. Then we update the length of ZigZag paths based on this variable.