100. Same Tree

Total Accepted: 109175
Total Submissions: 255839
Difficulty: Easy

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.

当然我的代码还可以缩短很多,但这样清晰明了

C++:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
 * 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!=NULL&&q==NULL){
            return false;
        }
        else if(p==NULL&&q!=NULL){
            return false;
        }
        else if(p!=NULL&&q!=NULL){
            if(p->val!=q->val){
                return false;
            }
            if(!isSameTree(p->left,q->left)){
                return false;
            }
            if(!isSameTree(p->right,q->right)){
                return false;
            }
        }
        return true;
    }
};

打个小广告

欢迎加入我的小专栏「基你太美」一起学习。