<AI/>
enru
Все статьи

Longest zigzag path in a binary tree

LeetCode 1372: Find the longest zigzag path in a binary tree with a modified depth-first search.

Сложность
Средняя
Автор
Denis Kolpakov
Опубликовано
Темы
#tree#binary tree
Открыть на LeetCode

Статья пока доступна только на английском.

Problem Description

Write a function that computes the length of the longest zigzag path in a binary tree. The path does NOT have to start at the root of the tree.

Input

A reference to the root of a binary tree.

Output

The length of the longest zigzag path.

Constraints

  • The number of nodes in the tree is from 1 to 50000

Examples

Input:

right left right 1 1 1 1 1 1 1 1

Answer: 3

Solution

To solve this problem, we need to recall how DFS works on trees and tweak it a little.

We want the depth-first search to return the length of the zigzag that starts to the left of the current node and the one that starts to the right. Then, going back up the tree, we can easily compute the path length (remember that if we go right from the current node, we must go left from the child, and vice versa):

  • For each node, the length of the zigzag starting from it to the left equals the zigzag length of its left child going right + 1
  • For each node, the length of the zigzag starting from it to the right equals the zigzag length of its right child going left + 1

If the path could only start at the root, these two values would be enough: we would just compare them at the end and return the maximum. But in this problem we need a third value so we don't lose paths that start deeper in the tree (let's call it maxLength).

For each node, we store in this value the maximum of four numbers:

  • The length of the zigzag starting from the current node to the right.
  • The length of the zigzag starting from the current node to the left.
  • maxLength of the left child
  • maxLength of the right child

This way, long paths of child nodes whose zigzag was "broken" on the way up during the depth-first search can "bubble up".

typescript
export type TreeNode = {
  val: number;
  left?: TreeNode;
  right?: TreeNode;
};
 
type DFSResult = {
  leftPathLength: number;
  rightPathLength: number;
  maxLength: number;
};
 
const dfs = (root?: TreeNode): DFSResult => {
  if (!root) {
    return {
      leftPathLength: 0,
      rightPathLength: 0,
      maxLength: 0,
    };
  }
 
  let leftPathLength = 0;
  let rightPathLength = 0;
  let leftMaxLength = 0;
  let rightMaxLength = 0;
 
  if (root.left) {
    const leftDFSRes = dfs(root.left);
    leftPathLength = leftDFSRes.rightPathLength + 1;
    leftMaxLength = leftDFSRes.maxLength;
  }
 
  if (root.right) {
    const rightDFSRes = dfs(root.right);
    rightPathLength = rightDFSRes.leftPathLength + 1;
    rightMaxLength = rightDFSRes.maxLength;
  }
 
  const maxLength = Math.max(Math.max(leftMaxLength, rightMaxLength), Math.max(leftPathLength, rightPathLength));
 
  return {
    leftPathLength,
    rightPathLength,
    maxLength,
  };
};
 
export const longestZigZag = (root?: TreeNode): number => {
  const { maxLength } = dfs(root);
  return maxLength;
};

Complexity Analysis

Time Complexity

O(n), since we perform a depth-first search over the binary tree, visiting all n of its nodes.

Space Complexity

O(n), since we use a recursive approach.

This means that in the worst case we keep n frames on the recursion stack.