[LeetCode 100] 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.

Diffculty
Easy

Similar Problems
[LeetCode 101] Symmetric Tree Easy

Analysis

递归处理,注意空节点的情况。

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

results matching ""

    No results matching ""