【LeetCode 100_二叉树_遍历】Same Tree

解法一:递归

 1 bool isSameTree(TreeNode* p, TreeNode* q)
 2 {
 3     if (p == NULL && q == NULL)
 4         return true;
 5     if ((p == NULL && q != NULL) || (p != NULL && q == NULL))
 6         return false;
 7     if (p->val != q->val)
 8         return false;
 9 
10     if (!isSameTree(p->left, q->left) || !isSameTree(p->right, q->right))
11         return false;
12 
13     return true;
14 }

解法二:非递归

 1 bool isSameTree(TreeNode* p, TreeNode* q)
 2 {
 3     queue<pair<TreeNode*, TreeNode*> > pq_queue;
 4     pq_queue.push(make_pair(p, q));
 5 
 6     while (!pq_queue.empty()) {
 7         TreeNode *pTmp = pq_queue.front().first;
 8         TreeNode *qTmp = pq_queue.front().second;
 9         pq_queue.pop();
10 
11         if (pTmp == NULL && qTmp == NULL)
12             continue;
13         if (pTmp == NULL || qTmp == NULL)
14             return false;
15         if (pTmp->val != qTmp->val)
16             return false;
17 
18         pq_queue.push(make_pair(pTmp->left, qTmp->left));
19         pq_queue.push(make_pair(pTmp->right, qTmp->right));
20     }
21     return true;
22 }

 

posted @ 2015-07-05 19:27  QingLiXueShi  阅读(148)  评论(0编辑  收藏  举报