LeetCode 1372: Longest ZigZag Path in a Binary Tree Solution

Master LeetCode problem 1372 (Longest ZigZag Path in a Binary Tree), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1372. Longest ZigZag Path in a Binary Tree

Problem Explanation

Explanation

To find the longest ZigZag path in a binary tree, we can perform a depth-first search (DFS) starting from each node. At each node, we can explore in two directions - left and right, and keep track of the length of the ZigZag path for that node. We can recursively traverse the tree while updating the maximum ZigZag path length encountered so far.

  1. Start by defining a helper function that performs DFS traversal.
  2. At each node, explore in both left and right directions.
  3. Update the maximum ZigZag path length encountered so far.
  4. Recursively traverse the tree and return the maximum ZigZag path length.

Time complexity: O(n) where n is the number of nodes in the tree Space complexity: O(n) for the recursive call stack

Solution Code

class Solution {
    int maxZigZag = 0;
    
    public int longestZigZag(TreeNode root) {
        if (root == null) return 0;
        dfs(root.left, 1, true);
        dfs(root.right, 1, false);
        return maxZigZag;
    }
    
    private void dfs(TreeNode node, int length, boolean isLeft) {
        if (node == null) {
            maxZigZag = Math.max(maxZigZag, length);
            return;
        }
        
        if (isLeft) {
            dfs(node.right, length + 1, false);
            dfs(node.left, 1, true);
        } else {
            dfs(node.left, length + 1, true);
            dfs(node.right, 1, false);
        }
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1372 (Longest ZigZag Path in a Binary Tree)?

This page provides optimized solutions for LeetCode problem 1372 (Longest ZigZag Path in a Binary Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1372 (Longest ZigZag Path in a Binary Tree)?

The time complexity for LeetCode 1372 (Longest ZigZag Path in a Binary Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1372 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1372 in Java, C++, or Python.

Back to LeetCode Solutions