zoukankan      html  css  js  c++  java
  • [leetCode]110.平衡二叉树

    在这里插入图片描述

    递归 自顶向下

    需要重复计算子树的高度

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public boolean isBalanced(TreeNode root) {
            if(root == null)return true;
            int sub = Math.abs(treeHeight(root.left) - treeHeight(root.right));
            if(sub <= 1){
                return isBalanced(root.left) && isBalanced(root.right);
            }else{
                return false;
            }
        }
    
        public int treeHeight(TreeNode root){
            if(root == null){
                return 0;
            }else{
                int leftHeight = treeHeight(root.left);
                int rightHeight = treeHeight(root.right);
                return Math.max(leftHeight, rightHeight) + 1;
            }
        }
    }
    

    递归 自底向上

    每个结点只需计算一次高度

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    final class TreeInfo{
        public int height;
        public boolean balanced;
    
        public TreeInfo(int h, boolean b){
            height = h;
            balanced = b;
        }
    }
    
    class Solution {
        public boolean isBalanced(TreeNode root) {
            return helper(root).balanced;
        }
    
        public TreeInfo helper(TreeNode root){
            if(root == null) return new TreeInfo(0,true);//空树大小为0
    
            TreeInfo left = helper(root.left);
            if(!left.balanced) return new TreeInfo(0,false);
    
            TreeInfo right = helper(root.right);
            if(!right.balanced) return new TreeInfo(0,false);
    
            if(Math.abs(left.height - right.height) < 2)return new TreeInfo(Math.max(left.height,right.height)+1,true);
            return new TreeInfo(0,false);
        }
    }
    
  • 相关阅读:
    C#开发规范
    Win32API使用技巧 -- 置顶应用
    Windows开发常用快捷键
    MarkDown简单语法回顾
    样本分布
    复变函数
    set theory
    Oscar的数理统计笔记本
    Oscar的拓扑笔记本
    c语言总结
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13860011.html
Copyright © 2011-2022 走看看