码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Same Tree

时间:2015-03-17 15:49:15      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:

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. 将两个树的根节点同时入队列
  3. 在队列不为空的前提下执行下列操作:
    1. 同时取队头结点,若都是空指针,则同时将其移除队列
    2. 若只有一个是空指针,则两个树不同,返回false
    3. 否则比较两个结点的元素值是否相等,若不等,则返回false
    4. 将队头结点的左右孩子指针全部分别入队列
  4. 最后若两个队列都为空,则两个树相同,否则不同。

下面贴上代码:

/**
 * 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) {
        queue<TreeNode*> p1;
        queue<TreeNode*> p2;
        p1.push(p);
        p2.push(q);
        TreeNode* t1;
        TreeNode* t2;
        while (!p1.empty()&&!p2.empty()){
            t1 = p1.front();
            t2 = p2.front();
            if (t1&&t2){
                if (t1->val != t2->val)
                    return false;
            }
            else if((t1&&!t2)||(!t1&&t2)){
                return false;
            }
            else{
                p1.pop();
                p2.pop();
                continue;
            }
            p1.pop();
            p2.pop();
            p1.push(t1->left);
            p1.push(t1->right);
            p2.push(t2->left);
            p2.push(t2->right);
        }
        if (p1.empty() && p2.empty())
            return true;
        else
            return false;
    }
};

[LeetCode]Same Tree

标签:

原文地址:http://blog.csdn.net/kaitankedemao/article/details/44342423

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!