zoukankan      html  css  js  c++  java
  • 38平衡二叉树

    题目描述

    输入一棵二叉树,判断该二叉树是否是平衡二叉树。
     
    思路:
    这题是基于上一题的求二叉树的深度写出来的代码,记住二叉树的每次递归返回的是啥很关键,
     
    这题自己理解的是调用helper函数返回高度,但是用了-1,只要不满足二叉树的要求就返回-1,这个函数是求高度的,本质还是按照写高度的那个函数那么写,但是提前处理了有问题就返回-1这种判断情况。
     
    class Solution {
    public:
        int helper(TreeNode* pRoot){
            if(pRoot == nullptr){
                return 0;
            }
            int left = helper(pRoot -> left);
            int right = helper(pRoot -> right);
            if(left == -1 || right == -1 || abs(left - right) > 1){
                return -1;
            }        
            return max(left,right) + 1;
        }
        bool IsBalanced_Solution(TreeNode* pRoot) {
            if(pRoot == nullptr){
                return true;
            }
            int judge = helper(pRoot);
            if(judge == -1){
                return false;
            }
            return true;
        }
    };
  • 相关阅读:
    macOS免费的NTFS读写软件
    Python模块和模块引用(一)
    Python Class (一)
    Ubuntu系统管理systemd
    Case Closed?
    The 'with' and 'as' Keywords
    Buffering Data
    rstrip
    堆排序
    堆 续9
  • 原文地址:https://www.cnblogs.com/dingxiaoqiang/p/8196038.html
Copyright © 2011-2022 走看看