讨论/《深度优先搜索》 - 练习:相同的树/
《深度优先搜索》 - 练习:相同的树
共 8 个回复

先贴上自己的代码

var isSameTree = function(p, q) {
    if (p == null && q == null) {
        return true;
    }
    if (p == null || q == null) {
        return false;
    }
    if (p.val != q.val) {
        return false;
    }

    return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
};

这个代码有两个可以注意的点

  1. p.val != q.val 才return false 千万不要用 p.val == q.val return true ,因为父节点的数值相等孩子结点不一定相等,换句话说父结点的数值不相等,两棵树就一定不相等。
  2. false && flase 的值为 false ,true && true 的值为true
1
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        }

        if (p != null && q != null) {
                return isSameTree(p.left, q.left) && isSameTree(p.right, q.right) && p.val == q.val;
        }

        return false;
    }
}
bool isSameTree(struct TreeNode* p, struct TreeNode* q){
    if (((p == NULL) && (q != NULL)) || ((p != NULL) && (q == NULL))) {
        return false;
    }
    if ((p == NULL) && (q == NULL)) {
        return true;
    }

    bool left = isSameTree(p->left, q->left);
    bool right = isSameTree(p->right, q->right);
    if ((p->val == q->val) && (left == true) && (right == true)) {
        return true;
    }
    return false;
}
class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if not p and not q: return True
        if not p or not q: return False
        return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q == null) return true;
        if(p == null || q == null) return false;
        if(p.val != q.val) return false;
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}
class Solution {

    //二叉树序列化
    private String serialize(TreeNode node) {
        if (node == null) {
            return "#";
        }

        return node.val + "," + serialize(node.left) + "," + serialize(node.right);
    }

    public boolean isSameTree(TreeNode p, TreeNode q) {

        String tree1 = serialize(p);
        String tree2 = serialize(q);
        return tree1.equals(tree2);
    }
}
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if(p==NULL && q==NULL){
            return true;
        }else if(p==NULL || q==NULL){
            return false;
        } else if (p->val != q->val) {
            return false;
        }else {
            return isSameTree(p->left, q->left)&&isSameTree(p->right,q->right);
        }
    }
};
class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        return (not p and not q) or (p != None and q !=None) and p.val == q.val and self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)