[leetcode] 100. Same Tree

Question:

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.

Solution 1:

非常简单的一道题,判断两棵树是否一致,就用层次遍历,每次先判断对应节点值是否相等,再判断结构是否相等,即一棵树有左子树而另一棵没有则为不相等。

/**
 * 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 isSameTree(TreeNode* p, TreeNode* q) {
        if (p == NULL && q == NULL) return true;
        if (p == NULL || q == NULL) return false;
        queue<TreeNode*> pque, qque;
        pque.push(p); qque.push(q);

        while (!qque.empty() && !pque.empty()) {
            // value
            TreeNode *pt = pque.front(), *qt = qque.front();
            pque.pop(); qque.pop();
            if (pt->val != qt->val) return false;

            //struct
            if (pt->left || qt->left) {
                if (pt->left && qt->left) {
                    pque.push(pt->left); qque.push(qt->left);
                } else {
                    return false;
                }
            }

            if (pt->right || qt->right) {
                if (pt->right && qt->right) {
                    pque.push(pt->right); qque.push(qt->right);
                } else {
                    return false;
                }
            }
        }

        return true;
    }
};

Solution 2:

想着使用递归做一遍,难点在于判断各种结构情况,判断结构的代码的主要思想是判断是否同时具有左孩子的情况,是否同时具有右孩子的情况,注意到这里面有一些情况是有包含的,代码也已经避免了那些情况,但还是感觉有点冗余。但是速度比上面的解法要快多了。

/**
 * 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 isSameTree(TreeNode* p, TreeNode* q) {
        if (p == NULL && q == NULL) return true;
        if (p == NULL || q == NULL) return false;
        // so p != NULL && q != NULL
        if (p->val != q->val) return false;
        //judge struct
        if (p->left == NULL && q->left == NULL) {
            if (p->right == NULL && q->right == NULL) return true;

            if (p->right == NULL || q->right == NULL) return false;

            return isSameTree(p->right, q->right);
        }

        if (p->left == NULL || q->left == NULL) return false;

        // so p->left != NULL and q->left != NULL
        if (p->right == NULL && q->right == NULL)
            return isSameTree(p->left, q->left);

        if (p->right == NULL || q->right == NULL) return false;

        // both left and right exist
        return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值