Longest ZigZag Path in a Binary Tree — LeetCode 1372 Python Solution
- Problem
- #1372
- Pattern
- Tree Traversal
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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).
Example
- Input
- root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1]
- Output
- 3
- Explanation
- Longest ZigZag path in blue nodes (right -> left -> right).
Python solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def longestZigZag(self, root: TreeNode) -> int:
def dfs(root, l, r):
if root is None:
return
nonlocal ans
ans = max(ans, l, r)
dfs(root.left, r + 1, 0)
dfs(root.right, 0, l + 1)
ans = 0
dfs(root, 0, 0)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1372. Longest ZigZag Path in a Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
On a study list
This problem is on LeetCode 75.
Frequently asked questions
- How hard is LeetCode 1372. Longest ZigZag Path in a Binary Tree?
- LeetCode 1372. Longest ZigZag Path in a Binary Tree is rated Medium on LeetCode.
- What topics does LeetCode 1372. Longest ZigZag Path in a Binary Tree cover?
- LeetCode 1372. Longest ZigZag Path in a Binary Tree is tagged Tree, Depth-First Search, Dynamic Programming and Binary Tree on LeetCode.