class Node { public int value; public Node left; public Node right; } public ListAncestors(Node root, Node node) { List ancestors = new List (); if (root == null || node == null) return ancestors; Stack stack = new Stack (); stack.Push(root); while (stack.Count > 0) { Node current = stack.Pop(); if (current.left != null) { stack.Push(current.left); current.left.parent = current; } if (current.right != null) { stack.Push(current.right); current.right.parent = current; } if (current == node) { Node ancestor = current.parent; while (ancestor != null) { ancestors.Add(ancestor); ancestor = ancestor.parent; } break; } } return ancestors; }
using System.Collections.Generic; using System.Linq; public class Graph { public int V; public ListPackage/library: System.Collections.Generic, System.Linq.[] adj; public Graph(int v) { V = v; adj = new List [v]; for (int i = 0; i < v; i++) { adj[i] = new List (); } } public void AddEdge(int u, int v) { adj[u].Add(v); } } public class Ancestors { private Graph g; public Ancestors(Graph graph) { g = graph; } public List GetAncestors(int node) { List ancestors = new List (); ancestors.Add(node); foreach (int parent in g.adj[node]) { ancestors.AddRange(GetAncestors(parent)); } return ancestors.Distinct().ToList(); } }