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

一、判断二叉树是不是平衡二叉树

方式一:

template<class T>     //深度
int BinaryTree<T>::_Depth(Node* root)              
{
    if (root)
    {
        int LeftDepth = _Depth(root->_LeftChild);
        int RightDepth = _Depth(root->_RightChild);
        return  LeftDepth > RightDepth ? LeftDepth + 1 : RightDepth + 1;
    }
    else
    {
        return 0;
    }
} 




bool _IsBalance()
{
    return IsBalance(_root) > 0 ? true : false;
}

template<class T>  
int BinaryTree<T>::IsBalance(Node* root)
{
    if (root == NULL)
    {
        return 0;
    }
    int _LeftHight = IsBalance(root->_LeftChild);
    if (_LeftHight < 0)
        return _LeftHight;
    int _RightHight = IsBalance(root->_RightChild);
    if (_RightHight < 0)
        return _RightHight;
    if (abs(_LeftHight - _RightHight) < 2)
        return 1 + (_LeftHight>_RightHight ? _LeftHight : _RightHight);
    else
        return -1;
}




 

方式二:

bool _IsBalance()
{
    int depth;
    return IsBalance(_root,&depth);
}

template<class T>
bool BinaryTree<T>::IsBalance(Node* root, int* depth)
{
    if (root == NULL)
    {
        *depth = 0;
        return true;
    }
    int LeftDepth, RightDepth;
    if (IsBalance(root->_LeftChild, &LeftDepth) && IsBalance(root->_RightChild, &RightDepth))
    {
        if (abs(LeftDepth - RightDepth) < 2)
        {
            *depth = 1 + (LeftDepth > RightDepth ? LeftDepth : RightDepth);
            return true;
        }
    }
    return false;
}


 

 

 

二、二叉树的镜像

template<class T>
void BinaryTree<T>::Mirror(Node* root)
{
    if (root == NULL)
        return;
    swap(root->_LeftChild, root->_RightChild);
    Mirror(root->_LeftChild);
    Mirror(root->_RightChild);
}


 

posted @ 2016-05-11 21:35  _in_the_way  阅读(102)  评论(0)    收藏  举报