LeetCode: Same Tree

思路:递归求解,比较当前节点,如果值相等,则继续比较左右子树,否则不必比较了,直接返回0

code:

class Solution {
public:
    bool isSameTree(TreeNode *p, TreeNode *q) {
        if(p && q){
            if(p->val == q->val)
                return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
            else
                return 0;
        }
        else if(q == NULL && p == NULL)
            return 1;
        return 0;
    }
};


你可能感兴趣的:(LeetCode: Same Tree)