二叉搜索树相关题目

//二叉查找树的第k大节点:利用二叉搜索树的中序遍历序列是递增排序的性质,递归实现
struct BinaryTreeNode{
    int m_nValue;
    BinaryTreeNode* m_pLeft;
    BinaryTreeNode* m_pRight;
};
BinaryTreeNode* FindKthNodeCore(BinaryTreeNode* pRoot, unsigned int & k){
    BinaryTreeNode* target = nullptr;
    if (pRoot->m_pLeft != nullptr) {
        target = FindKthNodeCore(pRoot->m_pLeft, k);
    }
    if (target == nullptr){
        if (k == 1)
            target = pRoot;
        else
            --k;
    }
    if (target == nullptr && pRoot->m_pRight != nullptr){
        target = FindKthNodeCore(pRoot->m_pRight, k);
    }
    return target;
}
BinaryTreeNode* FindKthNode(BinaryTreeNode* pRoot, unsigned int k){
    if (pRoot == nullptr || k < 1)
        return nullptr;
    return FindKthNodeCore(pRoot, k);
}
//二叉树的深度:二叉树的后序遍历
//题目一:求二叉树的深度
int DepthOfTree(BinaryTreeNode* pRoot){
    if (pRoot == nullptr)
        return 0;
    int left = DepthOfTree(pRoot->m_pLeft);
    int right = DepthOfTree(pRoot->m_pRight);
    int depth = max(left, right) + 1;
    return depth;
}
////////////////////////////////////////////////////////////
//题目二:判断一棵树是否是二叉平衡树
int DepthOfNode(BinaryTreeNode* pRoot){
    if (pRoot == nullptr)
        return 0;
    int left = DepthOfNode(pRoot->m_pLeft);
    int right = DepthOfNode(pRoot->m_pRight);
    return max(left, right) + 1;
}
bool IsBalancedTree(BinaryTreeNode* pRoot){
    if (pRoot == nullptr)
        return false;
    int left = DepthOfNode(pRoot->m_pLeft);
    int right = DepthOfNode(pRoot->m_pRight);
    int depthDiff = left - right;
    if (right > left)
        depthDiff = right - left;
    if (depthDiff > 1)
        return false;
    return IsBalancedTree(pRoot->m_pLeft) && IsBalancedTree(pRoot->m_pRight);
}
//后序遍历的方法:每个节点只需要遍历一次
bool IsBalanced(BinaryTreeNode* pRoot, int& depth){
    if (pRoot == nullptr){
        depth = 0;
        return true;
    }
    int left, right;
    if (IsBalanced(pRoot->m_pLeft, left)
        && IsBalanced(pRoot->m_pRight, right)){
        int diff = left - right;
        if (diff >= -1 && diff <= 1){
            depth = max(left, right) + 1;
            return true;
        }
    }
    return false;
}
bool IsBalancedTree2(BinaryTreeNode* pRoot){
    int depth = 0;
    return IsBalanced(pRoot, depth);
}
原文地址:https://www.cnblogs.com/songdanzju/p/7441971.html