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;
        }
    }
  • 相关阅读:
    iOS中GestureRecognizer的6大手势与代理方法详细使用
    使用pan手势实现抽屉效果
    mfc HackerTools释放资源
    mfc HackerTools防止程序双开
    FLV简介
    AAC简介
    H.264简介
    PCM简介
    YUV格式
    编译ffmpeg(第一次),实现JPG转MP4
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7208437.html
Copyright © 2011-2022 走看看