LeetCode 100. SameTree

#LeetCode 100. SameTree

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.

测试样例

/**
    * 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 == q && p == NULL)return true;
        // 如果一个到了尽头,而另一个没有,则说明树结构不同
        if (p == NULL || q == NULL)return false;
        // 如果树节点值不同,则树不同
        if (p->val != q->val)return false;
        // 对一个节点来说,它们的左节点和右节点都相等,才能保证这棵树相等
        return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
    }
};

猜你喜欢

转载自blog.csdn.net/qq_35533703/article/details/82585038