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

    题目描述

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

    解题思路

    递归判断子树是否是平衡二叉树,每次还需要返回子树的高度用以判断当前树是否是平衡的。

    实现

    public class Solution {
        private class Result{
            boolean isBalanced = false;
            int depth = 0;
    
            public Result(boolean isBalanced, int depth){
                this.isBalanced = isBalanced;
                this.depth = depth;
            }
        }
    
        public boolean IsBalanced_Solution(TreeNode root) {
            Result result = isBalanced(root);
            return result.isBalanced;
        }
    
        private Result isBalanced(TreeNode root) {
            if (root == null) return new Result(true, 0);
            Result left = isBalanced(root.left);
            Result right = isBalanced(root.right);
    
            int depth = left.depth > right.depth ? left.depth + 1 : right.depth + 1;
    
            if (!left.isBalanced || !right.isBalanced){
                return new Result(false,depth);
            }
    
            if (left.depth - right.depth > 1 || right.depth - left.depth > 1){
                return new Result(false,depth);
            }else {
                return new Result(true,depth);
            }
        }
    }
    
  • 相关阅读:
    ajax的post请求
    ajax的get请求
    浏览器缓存机制
    php和cookie
    php表单(2)
    php和表单(1)
    枚举for/in
    .Matrix-Beta冲刺的汇总博客
    .Matrix汇总博客
    小黄衫获得的感想
  • 原文地址:https://www.cnblogs.com/ggmfengyangdi/p/5794538.html
Copyright © 2011-2022 走看看