Longest Univalue Path

LeetCode Q 687- Longest Univalue Path

Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.
The length of path between two nodes is represented by the number of edges between them.

Example 1: Input: [5,4,5,1,1,null,5] ; Output: 2
Example 2: Input: [1,4,5,4,4,null,5] ; Output: 2

Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.

Solution:

Code:

int res = 0;
public int longestUnivaluePath(TreeNode root) {
  if (root == null) return res;
  dfs(root);
  return res;
}

private int dfs(TreeNode root) {
  if (root == null) return 0;

  int maxLen = 0, len = 0;

  int l = dfs(root.left), r = dfs(root.right);

  if (root.left != null && root.val == root.left.val) {
    maxLen += l + 1; len = l + 1;
  }

  if (root.right != null && root.val == root.right.val) {
    maxLen += r + 1; len = Math.max(len, r + 1);
  }

  res = Math.max(res, maxLen);

  return len;
}

   Reprint policy


《Longest Univalue Path》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC