Simple and Concise C++ DFS solution


  • 0
    W
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        
        bool isSubTreeHelper(TreeNode* s, TreeNode* t){
            if(!s&&!t)
                return true;
            if((s && !t)||(!s && t))
                return false;
            
            return s->val == t->val && isSubTreeHelper(s->left, t->left) && isSubTreeHelper(s->right, t->right);
        }
        
        bool isSubtree(TreeNode* s, TreeNode* t) {
            if(!s)
                return false;
            if(isSubTreeHelper(s,t))
                return true;
            
            return isSubtree(s->left,t)||isSubtree(s->right,t);
        }
    };
    

Log in to reply
 

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