【LeetCode】Same Tree

100. Same Tree

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 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     struct TreeNode *left;
 6  *     struct TreeNode *right;
 7  * };
 8  */
 9 bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
10     //其中一个为空另一个不为空的情况
11     if((!p && q) || (p && !q) )
12     {
13         return false;
14     }
15     //两个都为空
16     if(!p && !q)
17     {
18         return true;
19     }
20     //比较节点内容
21     if(p->val != q->val)
22     {
23         return false;
24     }
25     return (isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
26 }
只有当结构和节点的值都一样才返回true,所以25行要用&&将左子树和右子树全部比较完
如果用了||符号,那么就只能比较到两棵树的左子树的叶子节点
posted @ 2019-03-20 11:17  梅花五瓣  阅读(100)  评论(0)    收藏  举报