public static Node GetLowestCommonAncestor(Node root, Node p, Node q) { AncestryResult r = GetLowestCommonAncestorHelper(root, p, q); if (r.IsAncestor) { return(r.Node); } return(null); }
public static AncestryResult GetLowestCommonAncestorHelper(Node root, Node p, Node q) { if (root == null) { return(new AncestryResult(null, false)); } if (root == p && root == q) { return(new AncestryResult(root, true)); } AncestryResult rX = GetLowestCommonAncestorHelper(root.Left, p, q); if (rX.IsAncestor) { return(rX); } AncestryResult rY = GetLowestCommonAncestorHelper(root.Right, p, q); if (rY.IsAncestor) { return(rY); } if (rX.Node != null && rY.Node != null) { return(new AncestryResult(root, true)); } else if (root == p || root == q) { bool isAncestor = rX.Node != null || rY.Node != null; return(new AncestryResult(root, isAncestor)); } else { return(new AncestryResult(rX.Node != null ? rX.Node : rY.Node, false)); } }