LeetCode 相同的树100

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.

Example 1:

Input:     1         1
          / \       / \
         2   3     2   3
​
        [1,2,3],   [1,2,3]
​
Output: true

Example 2:

Input:     1         1
          /           \
         2             2
​
        [1,2],     [1,null,2]
​
Output: false

Example 3:

Input:     1         1
          / \       / \
         2   1     1   2
​
        [1,2,1],   [1,1,2]
​
Output: false

给定两个二叉树,编写一个函数来检查它们是否相同。

如果两个二叉树在结构上相同并且节点具有相同的值,则认为它们是相同的。

思路

1.如果p和q其中有一个是空树,那么不可能相等,返回false

2.每次递归查看值是否相等,如果相等,递归判断左右子树是否相等

3.其他情况都return false

扫描二维码关注公众号,回复: 2317082 查看本文章
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
    if(!p && !q){
        return true;
    }else if(p && q && (p->val == q->val)){
        return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
    }else{
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38362049/article/details/81162247
今日推荐