[leetcode] Same Tree

来源:互联网 发布:怎么用ps修淘宝主图 编辑:程序博客网 时间:2024/04/24 04:55

1. In-order Traverse and print tree. Compare the printed strings.

class Solution {public:    bool isSameTree(TreeNode *p, TreeNode *q) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        string sp;        string sq;        traverseAndPrint(p,sp);        traverseAndPrint(q,sq);        if(sp==sq)           return true;        else           return false;    }    void traverseAndPrint(TreeNode *p, string &str)    {        if(p==NULL) return;                str+="L";        traverseAndPrint(p->left,str);                char pval='0'+p->val;        str+="P"+pval;                str+="R";        traverseAndPrint(p->right,str);    }};


2. Use recursion to compare trees directly

class Solution {public:    bool isSameTree(TreeNode *p, TreeNode *q) {        // Start typing your C/C++ solution below        // DO NOT write int main() function                if(p==NULL && q==NULL)            return true;        else if(p==NULL||q==NULL)            return false;                if(p->val == q->val)        {            if(isSameTree(p->left,q->left))              return isSameTree(p->right,q->right);            else              return false;        }        else          return false;    }};
过了两个月再次写,一扁通过!
class Solution {public:    bool isSameTree(TreeNode *p, TreeNode *q) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(p==NULL && q==NULL)        {            return true;        }        else if(p==NULL || q==NULL)            return false;                if(p->val != q->val)            return false;        else if(!isSameTree(p->left,q->left))            return false;        else if(!isSameTree(p->right,q->right))            return false;                return true;    }};