Leetcode 100 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.

题目大意:

给定两个二叉树,写一个函数检查它们是否相等。两个二叉树如果结构相同并且对应的节点有相同的值,则被视作为相等。

归解法:

 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         //对应的节点同时为空,返回true
14         if(p == NULL && q == NULL)
15             return true;
16         //其他情况!p&&q,p&&!q, p&&q&&p->val != q->val 都返回false
17         else if(!p && q || p && !q || (p->val != q->val))
18                 return false;
19         return (isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
20     }
21 };

非递归:

建立两个队列分别进行层次遍历,进队时检查对应点是否相等

 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         if(!isSameNode(p, q))
14             return false;
15         if(!p && !q)
16             return true;
17         
18         queue<TreeNode*> lqueue;
19         queue<TreeNode*> rqueue;
20         lqueue.push(p);
21         rqueue.push(q);
22         while(!lqueue.empty() && !rqueue.empty())
23         {
24             TreeNode* lfront = lqueue.front();
25             TreeNode* rfront = rqueue.front();
26 
27             lqueue.pop();
28             rqueue.pop();
29             
30             if(!isSameNode(lfront->left, rfront->left))
31                 return false;
32             if(lfront->left && rfront->left)
33             {
34                 lqueue.push(lfront->left);
35                 rqueue.push(rfront->left);
36             }
37             
38             if(!isSameNode(lfront->right, rfront->right))
39                 return false;
40             if(lfront->right && rfront->right)
41             {
42                 lqueue.push(lfront->right);
43                 rqueue.push(rfront->right);
44             }
45         }
46         return true;
47     }
48     bool isSameNode(TreeNode* p, TreeNode *q)
49     {
50         if(!p && !q)
51             return true;
52         if((p && !q) || (!p && q) || (p->val != q->val))
53             return false;
54         return true;
55     }
56 };
原文地址:https://www.cnblogs.com/qinduanyinghua/p/5708157.html