zoukankan      html  css  js  c++  java
  • 剑指offer39 平衡二叉树

    一个错误代码

    class Solution {
    public:
        bool IsBalanced_Solution(TreeNode* pRoot) {
            return IsBalancedCore(pRoot,0);
        }
        bool IsBalancedCore(TreeNode* pRoot,int &depth){
            if(pRoot == NULL){
                depth = 0;
                return true;
            }
            int left = 0;
            int right = 0;
            if(IsBalancedCore(pRoot->left,left) && IsBalancedCore(pRoot->right,right)){
                int diff = left - right;
                if(diff <= 1 && diff >= -1){
                    depth = (left > right ? left:right) + 1;
                    return true;
                }
            }
            return false;
        }
    };

    若改成int depth = 0;

       return IsBalancedCore(pRoot,depth);

    就对了。IsBalancedCore这个函数的第二个参数是传参数,需要引用,用的时候不能为常量0,必须是一个参数。

    IsBalancedCore中depth参数必须&引用,如果不引用,

    depth = (left > right ? left:right) + 1;就无法修改depth,depth就一直是同一个值,无法记录depth的变化

    class Solution {
    public:
        bool IsBalanced_Solution(TreeNode* pRoot) {
            if(pRoot == NULL)
                return true;
            int depth;
            return IsBalanced_Core(pRoot,depth);
        }
        bool IsBalanced_Core(TreeNode* pRoot,int &depth){
            if(pRoot == NULL){
                depth = 0;
                return true;
            }
            int left,right;
            if(IsBalanced_Core(pRoot->left,left) && IsBalanced_Core(pRoot->right,right)){
                int diff = left - right;
                if(diff <= 1 && diff >= -1){
                    depth = left > right ? left+1 : right+1;
                    return true;
                }
            }
            return false;
        }
    };
     
  • 相关阅读:
    Systemd 指令
    2018年书单
    2017年书单
    Centos7 Devstack [Rocky] 重启后无法联网
    kvm虚拟机操作相关命令及虚拟机和镜像密码修改
    负载均衡原理-转
    用配置文件里面的参数值替换yaml模板中的变量值【python】
    linux工具之sar
    利用系统缓存优化程序的运行效率
    Elasticsearch单机部署
  • 原文地址:https://www.cnblogs.com/ymjyqsx/p/7194680.html
Copyright © 2011-2022 走看看