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;
        }
    }
  • 相关阅读:
    缓冲式I/O
    事件轮询接口
    博弈游戏
    多任务I/O之poll函数
    好的link
    做纹理处理的。。。
    快毕业了!
    语音处理的资料
    google图像搜索原理
    install opencv in centos
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7208437.html
Copyright © 2011-2022 走看看