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);
    }
    
  • 相关阅读:
    python标准库:Configparser模块
    git使用总结
    Scrapy笔记:使用scrapy shell url时出现403错误的解决办法
    Scrapy笔记:日志的使用
    Scrapy笔记:CrawSpider中rules中的使用
    django+nginx+mod_wsgi+apache网站部署
    关于URL编码 [转]
    FTP上传文件服务器python实现
    LVS高可用集群的配置
    Hadoop-hdfs安装与配置
  • 原文地址:https://www.cnblogs.com/songdanzju/p/7441971.html
Copyright © 2011-2022 走看看