zoukankan      html  css  js  c++  java
  • 面试题55_2:平衡二叉树

    输入一棵二叉树,判断该二叉树是否是平衡二叉树。

    在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树

    解题思路

    • 根据上一个题目“求二叉树的深度”,遍历每一个节点的左右子树深度
    • 通过“后序遍历”的特点,每个节点只需要遍历一次

    上代码(C++很香)

    法一:根据上一个题目“求二叉树的深度”,遍历每一个节点的左右子树深度(每个节点可能会被遍历多次)
    int maxD = 0;
    
    void dfs(TreeNode* pNode, int depth){
        // 叶子节点
        if(pNode->left == nullptr && pNode->right == nullptr){
            if(depth > maxD)
                maxD = depth;
            return ;
        }
        if(pNode->left != nullptr)
            dfs(pNode->left, depth + 1);
        if(pNode->right != nullptr)
            dfs(pNode->right, depth + 1);
    }
    
    int TreeDepth(TreeNode* pRoot){
    
        if(pRoot == nullptr)
            return 0;
    
        dfs(pRoot, 1);
        return maxD;
    }
    
    bool IsBalanced_Solution(TreeNode* pRoot){
        if(pRoot == nullptr)
            return true;
    
        int left = TreeDepth(pRoot->left);
        maxD= 0;
        int right = TreeDepth(pRoot->right);
        maxD = 0;
        int diff = abs(left - right);
        if(diff > 1)
            return false;
        return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
    }
    
    法二:通过“后序遍历”的特点,每个节点只需要遍历一次
    bool IsBalanced(TreeNode* pRoot, int* pDepth){
        if(pRoot == nullptr){
            *pDepth = 0;
            return true;
        }
    
        // 妙啊
        int left, right;
        if(IsBalanced(pRoot->left, &left) && IsBalanced(pRoot->right, &right)){
            int diff = left - right;
            if(diff <= 1 && diff >= -1)
            {
                *pDepth = 1 + (left > right ? left : right);
                return true;
            }
        }
    
        return false;
    }
    
    bool IsBalanced_Solution(TreeNode* pRoot){
        int depth = 0;
        return IsBalanced(pRoot, &depth);
    }
    
  • 相关阅读:
    @ResponseBody
    elselect vmodel初始化couponSelected.id 与 key="coupon.id" id数据类型要保持一致
    CentOS7安装k8s
    vuecli 搭建项目
    springboot+netty
    漏洞扫描器AWVS
    同一类控件批量初始化
    HQL manytoone 属性notfound, 引用外键记录不存在
    Netty 20211116 socket clientserver TCP/UDP
    安卓开发项目计划
  • 原文地址:https://www.cnblogs.com/flyingrun/p/13552123.html
Copyright © 2011-2022 走看看