Share my c# solution


  • 0
    D
    public class Solution {
    public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        return lowestCommonAncestor(root, p, q).commonAcc;    
    }
    
    private SearchData lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) return new SearchData(false, false, null);
        var leftSD = lowestCommonAncestor(root.left, p, q);
        if (leftSD.commonAcc != null) return leftSD;
        var rightSD = lowestCommonAncestor(root.right, p, q);
        if (rightSD.commonAcc != null) return rightSD;
        
        bool isp = ((leftSD.IsPFound) || (rightSD.IsPFound) || (root == p));
        bool isq = ((leftSD.IsQFound) || (rightSD.IsQFound) || (root == q));
        TreeNode ca = (isp && isq) ? root : null;
        
        return new SearchData(isp, isq, ca);
    }
    

    }

    public class SearchData{
    public bool IsPFound;
    public bool IsQFound;
    public TreeNode commonAcc;
    
    public SearchData(bool p, bool q, TreeNode node){
        IsPFound = p;
        IsQFound = q;
        commonAcc = node;    
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.