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);
    }
    
  • 相关阅读:
    json字符串数组判断其中
    json字符串数组判断其中
    jquery select chosen禁用某一项option
    数据库培训知识
    人员管理模块代码总结2015/8/12整理
    正则表达式在STARLIMS中的应用总结
    控件属性表
    Form-公共代码
    Server-Script公共代码
    Celient-Script公共代码
  • 原文地址:https://www.cnblogs.com/flyingrun/p/13552123.html
Copyright © 2011-2022 走看看