Same Tree

来源:互联网 发布:2016年cms系统排行榜 编辑:程序博客网 时间:2024/05/29 10:54

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.

Subscribe to see which companies asked this question

递归方法:

/** * Definition for a binary tree node. * 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!=NULL && q==NULL)            return false;        else        {            if(p->val != q->val)                return false;            else                return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);        }    }};
  非递归方法
/** * Definition for a binary tree node. * 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*> a1;       queue<TreeNode*> a2;       if(p==NULL && q==NULL) return true;       if((p && !q)||(!p && q)||(p->val!=q->val)) return false;       a1.push(p);       a2.push(q);       while(!a1.empty() && !a2.empty())       {           TreeNode* p1=a1.front();           a1.pop();           TreeNode* p2=a2.front();           a2.pop();           //一个重要的是NULL左右子树也得放进去 保持同步,如果是NULL,则他的左右子树不用放进去           if(p1==nullptr && p2==nullptr) continue;              if(p1==nullptr || p2==nullptr) return false;                            if( p1->val != p2->val) return false;                            a1.push(p1->left);              a1.push(p1->right);              a2.push(p2->left);              a2.push(p2->right);                          }              return true;    }};


0 0