[LeetCode] 110. Balanced Binary Tree

2022/1/9 6:07:33

本文主要是介绍[LeetCode] 110. Balanced Binary Tree,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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);
    }
}


这篇关于[LeetCode] 110. Balanced Binary Tree的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程