题目描述:

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.先看当前节点的数值是否相同,不同返回false。

  2.相同再往下延伸,看下面两个分支是否相同。

接着再决定结束条件:

  按照上面的比较条件,只有当两个节点都为NULL时返回,都存在时继续比较,其他情况都返回false。

代码:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool isSameTree(TreeNode* p, TreeNode* q) {
13         if(!q&&!p)
14             return true;
15         else if(q&&p)
16             if(p->val==q->val)
17                 return (isSameTree(p->left,q->left)&&isSameTree(p->right,q->right));
18             else
19                 return false;
20         else
21             return false;
22     }
23 };

 

他人代码:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool isSameTree(TreeNode* p, TreeNode* q) {
13         if(!q&&!p)
14             return true;
15         else if(q&&p)
16             return (q->val==p->val&&isSameTree(p->left,q->left)&&isSameTree(p->right,q->right));
17             //相比前人的代码,我的代码还是不够精简
18         else 
19             return false;
20     }
21 };

 

 

 

 

posted on 2018-02-07 20:32  宵夜在哪  阅读(99)  评论(0编辑  收藏  举报