Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created January 20, 2019 02:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/ccca8048f3e5f6af7c164f90c60a5a73 to your computer and use it in GitHub Desktop.
Save jianminchen/ccca8048f3e5f6af7c164f90c60a5a73 to your computer and use it in GitHub Desktop.
687 longest univalue path - code is from a casual coder blog
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _687_longest_univalue_path_IV
{
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
class Program
{
static void Main(string[] args)
{
}
public int LongestUnivaluePath(TreeNode root)
{
int maxThruCurrent = 0;
int maxCurrent = 0;
int maxGlobal = 0;
LongestUnivaluePath(root, ref maxThruCurrent, ref maxCurrent, ref maxGlobal);
return maxGlobal;
}
private void LongestUnivaluePath(TreeNode root,
ref int maxThruCurrent,
ref int maxCurrent,
ref int maxGlobal)
{
if (root == null) return;
int maxThruLeft = 0;
int maxLeft = 0;
LongestUnivaluePath(root.left, ref maxThruLeft, ref maxLeft, ref maxGlobal);
int maxThruRight = 0;
int maxRight = 0;
LongestUnivaluePath(root.right, ref maxThruRight, ref maxRight, ref maxGlobal);
maxThruCurrent = 0;
if (root.left != null && root.val == root.left.val)
{
maxThruCurrent += (1 + maxLeft);
maxCurrent = Math.Max(maxCurrent, 1 + maxLeft);
}
if (root.right != null && root.val == root.right.val)
{
maxThruCurrent += (1 + maxRight);
maxCurrent = Math.Max(maxCurrent, 1 + maxRight);
}
maxGlobal = Math.Max(maxGlobal, Math.Max(maxThruCurrent, maxCurrent));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment