zoukankan      html  css  js  c++  java
  • 二叉搜索树相关题目

    //二叉查找树的第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);
    }
    
  • 相关阅读:
    吹气球
    Leetcode 235
    什么是BPMN网关?
    BPMN中的任务和活动之间有什么区别?
    两款流程图设计推荐
    Activiti7.1, jBPM7.25, Camunda, Flowable6.3技术组成对比
    Flowable与activiti对比
    机器学习中的数学
    WopiServerTutorial
    如何整合Office Web Apps至自己开发的系统(二)
  • 原文地址:https://www.cnblogs.com/songdanzju/p/7441971.html
Copyright © 2011-2022 走看看