博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Balanced Binary Tree
阅读量:4075 次
发布时间:2019-05-25

本文共 1064 字,大约阅读时间需要 3 分钟。

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.

Java代码:

/** * Definition for binary tree * 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 depthOfLeft = getDepth(root.left, 1);        int depthOfRight = getDepth(root.right, 1);                if(Math.abs(depthOfRight-depthOfLeft) > 1){            return false;        }else{            return isBalanced(root.left) && isBalanced(root.right);        }    }        private int getDepth(TreeNode tree, int currentDepth){        if(tree == null){            return currentDepth;        }        return Math.max(getDepth(tree.left, currentDepth+1),                 getDepth(tree.right, currentDepth+1));    }}
 

转载地址:http://fnuni.baihongyu.com/

你可能感兴趣的文章
设置tabbaritem的title的颜色及按钮图片
查看>>
动态设置label的高度
查看>>
获取 一个文件 在沙盒Library/Caches/ 目录下的路径
查看>>
图片压缩
查看>>
检测缓存文件是否超时
查看>>
十进制字符串转十六进制字符串
查看>>
属性字符串(富文本)的使用
查看>>
cell上label的背景颜色在选中状态下改变的解决办法
查看>>
GPS定位
查看>>
地图、显示用户位置、大头针
查看>>
自定义大头针
查看>>
UIButton添加block点击事件
查看>>
利用runtime给类别添加属性
查看>>
本地推送
查看>>
FMDB的使用
查看>>
UIImage存为本地文件与UIImage转换为NSData
查看>>
[转]打印质数的各种算法
查看>>
[转]javascript with延伸的作用域是只读的吗?
查看>>
php的autoload与global
查看>>
IE不支持option的display:none属性
查看>>