Leetcode 树-100. 相同的树

2021-09-18 15:26:02 浏览数 (1)

1 DFS

代码语言:javascript复制
/**
 * 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 && !q) return true;
        if (!p || !q) return false;
        if (p->val == q->val) 
            return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
        return false;
    }
};

2 BFS

代码语言:javascript复制
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if (!p && !q) return true;
        if (!p || !q) return false;
        queue<TreeNode*> pp, qq;
        pp.push(p);
        qq.push(q);

        while(!qq.empty()) {
            TreeNode* p_node = pp.front(); pp.pop();
            TreeNode* q_node = qq.front(); qq.pop();
            if (p_node->val != q_node->val) return false;
            if ((!p_node->left && q_node->left) || (p_node->left && !q_node->left) ||(!p_node->right && q_node->right) || (p_node->right && !q_node->right))
                return false;
            if (p_node->left && q_node->left) {
                pp.push(p_node->left);
                qq.push(q_node->left);
            }
            if (p_node->right && q_node->right) {
                pp.push(p_node->right);
                qq.push(q_node->right);
            }
        }
        return true;
    }
};
dfs

0 人点赞