zoukankan      html  css  js  c++  java
  • 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 depth of the two subtrees of every node never differ by more than 1.

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        /**
         * 用一个INT 表示两种状态 当返回值大于等于0时 表示当前节点的深度,当返回值是-1时,表示不是平衡二叉树
         * @param root
         * @return
         */
        public int isBalancedHelper(TreeNode root) {
            if (root==null) {
                return 0;
            }
            int l = isBalancedHelper(root.left);
            int r = isBalancedHelper(root.right);
            if (l==-1||r==-1) {
                //左右子树有一个不是平衡二叉树,就不是平衡二叉树
                return -1;
            }
            if (Math.abs(l-r)>1) {
                //左右子树高度差大于1 不是平衡二叉树
                return -1;
            } else {
                return Math.max(l, r) + 1;
            }
        }
    
        /**
         * 平衡二叉树 左右子树是平衡二叉树 且 左右子树高度差小于等于1
         * @param root
         * @return
         */
        public boolean isBalanced(TreeNode root) {
            return isBalancedHelper(root)>=0;
        }
    }
  • 相关阅读:
    关于汉密尔顿回路
    hdu 3018 Ant Trip
    hdu 1116 Play on Words
    关于欧拉回路、欧拉通路的一些定理及推论
    hdu 1531 King
    hdu 3440 House Man
    hdu 3666 THE MATRIX PROBLEM
    hdu 1384 Intervals
    关于差分约束系统
    hdu 1878 欧拉回路
  • 原文地址:https://www.cnblogs.com/23lalala/p/3506852.html
Copyright © 2011-2022 走看看