bool IsSubtree(BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2) { if (pRoot1 == NULL || pRoot2 == NULL) { return false; } stack<BinaryTreeNode*> stk; stk.push(pRoot1); while (!stk.empty()) { BinaryTreeNode *tmp = stk.top(); stk.pop(); if (tmp->m_nValue == pRoot2->m_nValue) { stack<BinaryTreeNode*> first; BinaryTreeNode *f; stack<BinaryTreeNode*> second; BinaryTreeNode *s; first.push(tmp); second.push(pRoot2); bool find = true; while (!first.empty()) { f = first.top(); first.pop(); s = second.top(); second.pop(); if (f->m_nValue != s->m_nValue) { find = false; break; } if (s->m_pLeft != NULL) { if (f->m_pLeft == NULL) { find = false; break; } else { first.push(f->m_pLeft); second.push(s->m_pLeft); } } if (s->m_pRight != NULL) { if (f->m_pRight == NULL) { find = false; break; } else { first.push(f->m_pRight); second.push(s->m_pRight); } } } if (find == true && first.empty()) { return true; } } if (tmp->m_pLeft != NULL) { stk.push(tmp->m_pLeft); } if (tmp->m_pRight != NULL) { stk.push(tmp->m_pRight); } } return false; }
2.