Leetcode - 100. Same Tree

Given two binary trees, 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.

Solution:

/**
 * 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) {
        std::queue<TreeNode*> Q;
        Q.push(p);
        Q.push(q);
        
        while(!Q.empty())
        {
            auto pp = Q.front(); Q.pop();
            auto qq = Q.front(); Q.pop();
            
            if(!pp && !qq) continue;
            if(!pp || !qq) return false;
            if(pp->val != qq->val) return false;
            
            Q.push(pp->left);
            Q.push(qq->left);
            Q.push(pp->right);
            Q.push(qq->right);
        }
        return true;
    }
};

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

你可能感兴趣的:(leetcode,二叉树)