C# solution: find the same value then check


  • 0
    B
    public class Solution 
    {
        private bool result = false;
        public bool IsSubtree(TreeNode s, TreeNode t) 
        {
            FindSameValue(s, t);
            return result;
        }
    
        private void FindSameValue(TreeNode s, TreeNode t)
        {
            if (result) return;
            if (s == null || t == null) return;
    
            if (s.val == t.val)
            {
                // find subtree
                var oneResult = IsSubTreeDFS(s, t);
    
                if (oneResult)
                {
                    result = true;
                    return;
                }
            }
    
            FindSameValue(s.left, t);
            FindSameValue(s.right, t);
        }
    
        private bool IsSubTreeDFS(TreeNode s, TreeNode t)
        {
            if (s == null && t == null) return true;
    
            if (s == null || t == null) return false;
    
            if (s.val == t.val)
            {
                return IsSubTreeDFS(s.left, t.left) && IsSubTreeDFS(s.right, t.right);
            }
    
            return false;
        }
    }
    

Log in to reply
 

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