zoukankan      html  css  js  c++  java
  • 平衡二叉树 --剑指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);
        }
    }
  • 相关阅读:
    EasyUI tab
    CC和他的AE86
    Spreading the Wealth UVA
    Ultra-QuickSort POJ
    区间完全覆盖问题(贪心)
    Mod Tree HDU
    Snakes and Ladders LightOJ
    There is no SSR CSU
    X问题 HDU
    斐波那契数列
  • 原文地址:https://www.cnblogs.com/nlw-blog/p/12444883.html
Copyright © 2011-2022 走看看