Following is the O(min(m, n)) Solution where m = number of nodes in tree1 and n = number of nodes in tree2.
The recursion uses the implicit stack. In order to implement it iteratively we need to use in-order traversal logic.
following is the code.
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;
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);
}
};
answered
22 Jun '13, 08:50
Laiq Ahmed
0●1
accept rate:
0%