[LeetCode]Same Tree

来源:互联网 发布:淘宝我的卡券包在哪里 编辑:程序博客网 时间:2024/06/05 06:52

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;    }};
0 0
原创粉丝点击