[Leetcode] Same tree判断是否为相同树

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.

二叉树相同:一、结构相同;二、对应节点上的值相同。

思路:层次遍历,维护两个队列,判断对应节点的值是否相等。值得注意的有:一、节点均为空时,再次循环取队首元素,有两种情况,i)q、p就为空,则不满足再次循环条件时,此时q==p为空,两树相同;ii) 到叶节点时,将其左右孩子压入队列时,对应的均为空,则可以再次循环,取队首元素,重新对比;二、有一个节点为空时,因为第一种情况,排除了两者都为NULL,所以这里只是其中有一个为NULL,则返回false;三、对应节点值不等,则返回false;然后依次将两树的左右孩子压入队列中继续循环。

值得注意:若是循环体中,将两树的左右孩子压入队列中,加判断左右孩子是否存在,存在则压,否则不压,则,while条件中既不能用||也不能用&&,因为,||时,会对空队列取首元素,&&时,会造成不能而等,如{1,1}和{1,1,1},所以不能压入时加if判断。

当然可以改变代码的写法,这样可以加if判断,见Grandyang的博客。别的遍历方式应该也能达到同样的实现判断两树是否相同。

 1 /**
 2  * Definition for binary tree
 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     {
14         queue<TreeNode *> pQ;
15         queue<TreeNode *> qQ;
16 
17         pQ.push(p);
18         qQ.push(q);
19         while( !pQ.empty()&& !qQ.empty())  //这里||和&&都可以AC,
20         {                     
21             TreeNode *pNode=pQ.front();
22             TreeNode *qNode=qQ.front();
23             pQ.pop();
24             qQ.pop();
25 
26             //同时不存在
27             if(pNode==NULL&&qNode==NULL)
28                 continue;
29             //有一个不存在
30             if(pNode==NULL||qNode==NULL)
31                 return false;
32             
33             if(pNode->val !=qNode->val)
34                 return false;
35 
36             pQ.push(pNode->left);
37             pQ.push(pNode->right);
38             qQ.push(qNode->left);
39             qQ.push(qNode->right);
40         }    
41         return true;
42     }
43 };

方法二:

递归大法。终止条件上见;递归式,要注意的是,左右子树必须同时一样才行,所以要用&&

/**
 * Definition for binary tree
 * 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 true;
        else if(p==NULL||q==NULL)   return false;
        else if(p->val !=q->val)    return false;

        return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
    }
};

 

posted @ 2017-06-11 09:43  王大咩的图书馆  阅读(408)  评论(0编辑  收藏  举报