A variation to Binary Tree iteration.
class Solution { bool isSame(TreeNode *p1, TreeNode *p2) { if (!p1 && !p2) return true; if( (!p1 && p2) || (p1 && !p2) || (p1->val != p2->val)) return false; return isSame(p1->left, p2->left) && isSame(p1->right, p2->right); } public: /** * @param T1, T2: The roots of binary tree. * @return: True if T2 is a subtree of T1, or false. */ bool isSubtree(TreeNode *T1, TreeNode *T2) { if (!T2) return true; if (!T1 && T2) return false; queue<TreeNode *> q; q.push(T1); while(!q.empty()) { auto p = q.front(); q.pop(); if(isSame(p, T2)) return true; if (p->right) q.push(p->right); if (p->left) q.push(p->left); } return false; } };