[LeetCode] Same Tree

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

判断两棵树是否相同:1)如果两棵树的对应节点都为空,返回true。2)如果只有1课树的节点为空,返回false。3)如果两棵树的当前节点值相同,则递归判断下一个对应的节点。4)如果都不满足以上,则返回false。

class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if (p == nullptr && q == nullptr)
            return true;
        if (p == nullptr || q == nullptr)
            return false;
        if (p->val == q->val)
            return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
        return false;
    }
};
// 0 ms

以上过程的简洁写法。

class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if (p == nullptr || q == nullptr)
            return p == q;
        return (p->val == q->val) && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
    }
};
// 3 ms

 

posted @ 2017-07-16 21:46  immjc  阅读(129)  评论(0编辑  收藏  举报