[LeetCode]Same Tree

来源:互联网 发布:java rpc 客户端 编辑:程序博客网 时间:2024/04/19 22:04
struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {//this problem is similar to symmetric tree, and can be solved in the same way//both recursive solution and iterative solution here//iterative one we can use BFS thought, but with two BFS route, and the order to push the child in queue//should be adjusted accordinglypublic:bool Recursive(TreeNode* a, TreeNode* b){if(!a && !b)return true;if(!a || !b) return false;if(a->val != b->val)return false;return Recursive(a->left, b->left)&&Recursive(a->right, b->right);}bool Iterative(TreeNode* a, TreeNode* b){queue<TreeNode*> left, right;left.push(a); right.push(b);while (!left.empty() && !right.empty()){TreeNode* curLeft = left.front(); TreeNode* curRight = right.front();left.pop(); right.pop();if(!curLeft && !curRight) continue;if(!curLeft || !curRight) return false;if(curLeft->val != curRight->val) return false;left.push(curLeft->left); left.push(curLeft->right);right.push(curRight->left); right.push(curRight->right);}return true;}bool isSameTree(TreeNode *p, TreeNode *q) {// Start typing your C/C++ solution below// DO NOT write int main() function//return Recursive(p, q);return Iterative(p, q);}};

second time

/** * 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 isSameTreeUtil(TreeNode* p, TreeNode* q)    {        if(p == NULL && q == NULL) return true;        if(p == NULL && q != NULL) return false;        if(p != NULL && q == NULL) return false;        if(p->val == q->val)        {            return isSameTreeUtil(p->left, q->left) && isSameTreeUtil(p->right, q->right);        }        else return false;    }    bool isSameTree(TreeNode *p, TreeNode *q) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        return isSameTreeUtil(p, q);    }};


原创粉丝点击