二叉树相关面试的集锦(三)

 一、将二叉搜索树转换为一个排序的双向链表

 

Node<K>* _SearchBinaryTreeToLinkList()
{
    Node<K>* Head = _root;
    while (Head && Head->Left)   //查找双向链表的头结点
    {
        Head = Head->Left;
    }
    Node<K>* prev = NULL;
    SearchBinaryTreeToLinkList(_root,prev);
    return Head;
}

//类似于二叉树的中序线索化

template<class K>
void SearchBinaryTree<K>::SearchBinaryTreeToLinkList(Node<K>* root,Node<K>*& prev)
{
    if (root)
    {
        SearchBinaryTreeToLinkList(root->Left,prev);
        if (prev && prev->Right == NULL)    //只有右子树为空的是后需要连接
        {
            prev->Right = root;
        }
        root->Left = prev;      //root->Left 必须得连接到 prev 上
        prev = root;
        SearchBinaryTreeToLinkList(root->Right, prev);
    }
}


 

二、判断二叉树是不是完全二叉树

 

 

template<class T>
bool BinaryTree<T>::IsComplete(Node* root)
{
    if (root == NULL)
    {
        return true;
    }
    queue<Node*> NodePointerQueue;
    NodePointerQueue.push(root);
    bool CheckPrev = false;
    while (!NodePointerQueue.empty())
    {
        root = NodePointerQueue.front();
        NodePointerQueue.pop();
        if (root->_LeftChild)
        {
            if (CheckPrev)
                return false;
            NodePointerQueue.push(root->_LeftChild);
        }
        else
            CheckPrev = true;

        if (root->_RightChild)
        {    
            if (CheckPrev)
                return false;
            NodePointerQueue.push(root->_RightChild);
        }
        else
            CheckPrev = true;
    }
    return true;
}



 

posted @ 2016-05-13 00:41  _in_the_way  阅读(79)  评论(0编辑  收藏  举报