Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created September 20, 2023 23:18
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/df702af0703ab8824e7d3315896948de to your computer and use it in GitHub Desktop.
Save jianminchen/df702af0703ab8824e7d3315896948de to your computer and use it in GitHub Desktop.
1361 validate binary tree nodes - C# solution
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1361_Validate_binary_tree_nodes
{
class Program
{
static void Main(string[] args)
{
var test = new Program();
var result = test.ValidateBinaryTreeNodes(4, new int[]{1, -1, 3, -1}, new int[]{2, -1, -1, -1});
//var result2 = test.ValidateBinaryTreeNodes(4, new int[]{1, -1, 3, -1}, new int[]{2, 3, -1, -1});
//var result3 = test.ValidateBinaryTreeNodes(2, new int[] { 1, 0 }, new int[] { -1, -1 });
}
/// <summary>
/// 1351. Validate binary tree nodes
/// 1. Binary tree must have a root. This is a node with no incoming edges - that is, the root has no parent;
/// 2. Every node other than the root must have exactly one parent;
/// 3. The tree must be connected - every node must be reachable from one node ( the root);
/// 4. There cannot be a cycle.
/// </summary>
/// <param name="n"></param>
/// <param name="leftChild"></param>
/// <param name="rightChild"></param>
/// <returns></returns>
public bool ValidateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild)
{
var inDegree = new int[n];
int root = -1;
for (int i = 0; i < leftChild.Length; i++)
{
if (leftChild[i] != -1 && inDegree[leftChild[i]] == 1)
{
return false;
}
else if(rightChild[i]!= -1 && inDegree[rightChild[i]] == 1)
{
return false;
}
if (leftChild[i] != -1)
{
inDegree[leftChild[i]]++;
}
if (rightChild[i] != -1)
{
inDegree[rightChild[i]]++;
}
}
// Find root and also check for multiple roots
for (int i = 0; i < leftChild.Length; i++)
{
if (inDegree[i] == 0)
{
if (root == -1)
{
root = i;
}
else // we have multiple root, return false;
{
return false;
}
}
}
if (root == -1)
{
return false;
}
return countNodes(leftChild, rightChild, root) == n;
}
private int countNodes(int[] leftChild, int[] rightChild, int root)
{
if (root == -1)
{
return 0;
}
return 1 + countNodes(leftChild, rightChild, leftChild[root]) + countNodes(leftChild, rightChild, rightChild[root]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment