Created
January 19, 2019 19:24
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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