2014阿里巴巴笔试题


题目:两棵二叉树T1和T2,T1的节点数是百万量级,T2的节点数一千以内,请给出判断T2是否T1子树的可行算法。

分析

首先想到的是递归,但是T1的数量级太大,递归会导致栈溢出,于是以非递归实现。

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;  
}  






你可能感兴趣的:(C++,阿里巴巴,校园招聘,笔试面试)