【Leetcode】 100. 相同的树

Given the roots of two binary trees p and q, write a function to check if they are the same or not.

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

Example 1:
【Leetcode】 100. 相同的树_第1张图片

Input: p = [1,2,3], q = [1,2,3]
Output: true

Example 2:
【Leetcode】 100. 相同的树_第2张图片

Input: p = [1,2], q = [1,null,2]
Output: false

Example 3:
【Leetcode】 100. 相同的树_第3张图片

Input: p = [1,2,1], q = [1,1,2]
Output: false

Constraints:

The number of nodes in both trees is in the range [0, 100].
-104 <= Node.val <= 104

Thought:
(BFS)使用两个队列分别存储两个二叉树的节点,然后逐个比较它们的值以及左右子树是否相同。如果两个节点的值不同或者它们的左右子树的情况不同,就说明这两个二叉树不相同。如果两个队列都为空,说明两个二叉树完全相同。

AC:

/*
 * @lc app=leetcode.cn id=100 lang=cpp
 *
 * [100] 相同的树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if(p == nullptr && q == nullptr)
        {
            return true;
        }
        else if(p == nullptr || q == nullptr)
        {
            return false;
        }
        queue <TreeNode*> queue1, queue2;
        queue1.push(p);
        queue2.push(q);
        while(!queue1.empty() && !queue2.empty())
        {
            auto node1 = queue1.front();
            queue1.pop();
            auto node2 = queue2.front();
            queue2.pop();
            if(node1->val != node2->val)
            {
                return false;
            }
            auto left1 = node1->left, right1 = node1->right, left2 = node2->left, right2 = node2->right;
            if((left1 == nullptr) ^ (left2 == nullptr))
            {
                return false;
            }
            if((right1 == nullptr) ^ (right2 == nullptr))
            {
                return false;
            }
            if(left1 != nullptr)
            {
                queue1.push(left1);
            }
            if(right1 != nullptr)
            {
                queue1.push(right1);
            }
            if(left2 != nullptr)
            {
                queue2.push(left2);
            }
            if(right2 != nullptr)
            {
                queue2.push(right2);
            }
        }
        return queue1.empty() && queue2.empty();
    }
};
// @lc code=end

【Leetcode】 100. 相同的树_第4张图片

你可能感兴趣的:(Leetcode,leetcode,算法,职场和发展)