• 平衡二叉树 --剑指offer


    题目描述

    输入一棵二叉树,判断该二叉树是否是平衡二叉树。
    从上往下计算树的深度 有重复计算
    public class Solution {
        public boolean IsBalanced_Solution(TreeNode root) {
            if(root == null) return true;
            if(Math.abs(getDepth(root.left)-getDepth(root.right)) > 1) return  false;
            return IsBalanced_Solution(root.left) &&  IsBalanced_Solution(root.right);
        }
    
        private int getDepth(TreeNode root) {
            if(root == null){
                return 0;
            }
            return Math.max(1+getDepth(root.left),1+getDepth(root.right));
        }
    
    }

    从下往上计算 相当后序遍历

    public class Solution {
        public boolean IsBalanced_Solution(TreeNode root) {
            return getDepth(root) == -1?false:true;
        }
    
        public int getDepth(TreeNode node){
            if(node == null){
                return 0;
            }
            int left=0,right=0;
            if(node.left != null){
                left=getDepth(node.left);
            }
            if(left == -1) return -1;
            if(node.right != null){
                right=getDepth(node.right);
            }
            if(right == -1) return -1;
            return Math.abs(left-right) >1 ?-1:1+Math.max(left,right);
        }
    }
  • 相关阅读:
    Unix Shell常用命令
    传输信号
    硬盘 光驱 跳线问题
    常见病毒类型
    Unix操作系统文件结构
    数字模拟信号 单双信道传输
    双绞线
    Unix操作系统目录存放内容
    EasyRecovery数据恢复工具
    什么叫做泛解析
  • 原文地址:https://www.cnblogs.com/nlw-blog/p/12444883.html
Copyright © 2020-2023  润新知