ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[LeetCode] 110. Balanced Binary Tree

2022-01-09 01:33:36  阅读:217  来源: 互联网

标签:Info Binary TreeNode val Tree hight isBalanced Balanced root


Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Example1:

Input: root = [3,9,20,null,null,15,7]
Output: true

Example2:

Input: root = [1,2,2,3,3,null,null,4,4]
Output: false

Example3:

Input: root = []
Output: true

Constraints:

  • The number of nodes in the tree is in the range [0, 5000].
  • -104 <= Node.val <= 104

所谓的平衡二叉树,就是每一棵树左右子树的高度差小于1。这道题可以用递归,但是判断当前树是不是平衡,就需要高度的信息,所以递归的时候要返回这个信息。除此之外,每棵子树是不是平衡的信息也要返回,因为有的时候在底层不平衡,但是上层的左右子树差是1。
注意:

  • 有的时候递归需要一些其他辅助的信息,这时候递归返回的是一个class,里面都包含了需要的信息。
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Info {
    boolean isBalanced;
    int hight;
    Info(boolean isBalanced, int hight){
        this.isBalanced = isBalanced;
        this.hight = hight;
    }
}

class Solution {
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        Info rst = helper(root);
        return rst.isBalanced;
    }
    
    private Info helper(TreeNode root) {
        if (root == null) {
            return new Info(true, 0);
        }
        
        Info l = helper(root.left);
        Info r = helper(root.right);
        
        
        
        return new Info(l.isBalanced && r.isBalanced && (Math.abs(l.hight - r.hight) < 2), 
                    Math.max(l.hight, r.hight) + 1);
    }
}

标签:Info,Binary,TreeNode,val,Tree,hight,isBalanced,Balanced,root
来源: https://www.cnblogs.com/codingEskimo/p/15780140.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有