C++ and Java solutions


  • 0
    A

    C++

    class Solution {
    public:
        bool isSame(TreeNode *s, TreeNode *t) {
            if (!s && !t)
                return true;
            
            if (!s && t || s && !t)
                return false;
            
            return s->val == t->val && isSame(s->left, t->left) && isSame(s->right, t->right);
        }
    
        bool isSubtree(TreeNode* s, TreeNode* t) {
            if (!s)
                return !t;
            return isSame(s, t) || isSubtree(s->left, t) || isSubtree(s->right, t);
        }
    };
    

    Java

    public class Solution {
        private boolean isSame(TreeNode s, TreeNode t) {
            if (s == null && t == null) {
                return true;
            }
            
            if (s != null && t == null || s == null && t != null) {
                return false;
            }
            
            return s.val == t.val && isSame(s.left, t.left) && isSame(s.right, t.right);
        }
        
        public boolean isSubtree(TreeNode s, TreeNode t) {
            if (s == null) {
                return t == null;
            }
            
            return isSame(s, t) || 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.