Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created January 19, 2019 19:24
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/d5a82d3fc70c69cb87f9275c78302e40 to your computer and use it in GitHub Desktop.
Save jianminchen/d5a82d3fc70c69cb87f9275c78302e40 to your computer and use it in GitHub Desktop.
687 longest univalue path - study case: I wrote the code but the code failed on a test case.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _687_longest_univalue_path_III
{
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)
{
RunTestcase1();
}
public static void RunTestcase1()
{
var node5 = new TreeNode(1);
var node5B = new TreeNode(5);
var node5C = new TreeNode(5);
var node5D = new TreeNode(5);
var node5E = new TreeNode(5);
node5.left = node5B;
node5.right = node5C;
node5B.left = node5D;
node5B.right = node5E;
var result = LongestUnivaluePath(node5);
}
/// <summary>
///
/// </summary>
/// <param name="root"></param>
/// <returns></returns>
public static int LongestUnivaluePath(TreeNode root)
{
int crossPath = 0;
postOrderTraversal(root, ref crossPath);
return crossPath;
}
/// <summary>
///
/// </summary>
/// <param name="root"></param>
/// <param name="crossPath"></param>
/// <returns></returns>
private static int postOrderTraversal(TreeNode root, ref int crossPath)
{
if (root == null)
return 0;
// structure post order traversal clearly
var left = postOrderTraversal(root.left, ref crossPath);
var right = postOrderTraversal(root.right, ref crossPath);
// deal with root node related calculation
var currentCrossPath = 0;
if (root.left != null && root.val == root.left.val)
{
left++;
currentCrossPath += left;
}
if (root.right != null && root.val == root.right.val)
{
right++;
currentCrossPath += right;
}
crossPath = currentCrossPath > crossPath ? currentCrossPath : crossPath;
return Math.Max(left, right);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment