zoukankan      html  css  js  c++  java
  • [LeetCode] 110. Balanced Binary Tree Java

    题目:

    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 depth of the two subtrees of every node never differ by more than 1.

    题意及分析:给出一课二叉树,判断是否是二叉平衡树。使用递归,分别求出左右子树的高度,然后相减,看是否符合条件,若符合,则分别判断左右子节点是否符合。

    代码:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public boolean isBalanced(TreeNode root) {
            if(root==null) return true;
            int left = count(root.left);
            int right =count(root.right);
            return Math.abs(left - right) <= 1 && isBalanced(root.left) && isBalanced(root.right);
        }
    
        public int count(TreeNode node){        //求一棵树的高度,为左右子树的最大高度+1
            if(node==null) return 0;
            return Math.max(count(node.left),count(node.right))+1;
        }
    }
  • 相关阅读:
    全选+批量删除
    ssm异步上传图片
    抽象类与接口区别
    请求转发和重定向区别
    switch
    一道有点绕弯,考察的知识也是最基础的题
    线程安全之集合
    会话跟踪技术
    关于异常说明
    mybatis总结(三)之多表查询
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7208437.html
Copyright © 2011-2022 走看看