LeetCode-110-Balanced Binary Tree(平衡二叉树)
来源:互联网 发布:主提女装淘宝店有吗 编辑:程序博客网 时间:2024/06/05 06:44
Q:
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.
Analysis:
使用递归计算树的高度,若当前结点满足平衡二叉树性质,仍需要判断该结点的左右子树是否满足平衡二叉树。
Code:
/** * 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 = deep(root.left); int right = deep(root.right); // 若本节点满足平衡二叉树,判断左右子树是否满足 if (Math.abs(left - right) <= 1) { return isBalanced(root.left) && isBalanced(root.right); } else { return false; } } public static int deep(TreeNode root) { int depthLeft, depthRight; if (root == null) { return 0; } if (root.right == null && root.left == null) { return 1; } else { depthLeft = deep(root.left); depthRight = deep(root.right); } return 1+(depthLeft>depthRight?depthLeft:depthRight); }}
阅读全文
0 0
- 【LeetCode】Balanced Binary Tree,平衡二叉树
- [LeetCode] Balanced Binary Tree 平衡二叉树
- Leetcode Balanced Binary Tree 平衡二叉树
- LeetCode 110 Balanced Binary Tree(平衡二叉树)(*)
- LeetCode-110-Balanced Binary Tree(平衡二叉树)
- Balanced Binary Tree 判断是否平衡二叉树 @LeetCode
- LeetCode | Balanced Binary Tree(平衡二叉树)
- leetcode Balanced Binary Tree 平衡二叉树判定
- leetcode 110. Balanced Binary Tree-平衡二叉树|深度遍历
- LeetCode 110. Balanced Binary Tree(平衡二叉树)
- LeetCode:Balanced Binary Tree(平衡二叉树的判断)
- Leetcode 110. Balanced Binary Tree 平衡二叉树 解题报告
- leetcode -- 110. Balanced Binary Tree 【二叉树是否平衡】
- 【LeetCode笔记】Balanced Binary Tree 高度平衡二叉树
- 【平衡二叉树】leetcode 110. Balanced Binary Tree
- Balanced Binary Tree 二叉平衡树
- 平衡二叉树---Balanced Binary Tree
- lintcode balanced-binary-tree 平衡二叉树
- Python for...else
- 最长不下降子序列
- Qt之QWidget/QDialog/QMainWindow
- 概念 Qt
- 工具类—Java下载远程文件到本地
- LeetCode-110-Balanced Binary Tree(平衡二叉树)
- CBC模式的DES加密算法(加密字符串、加密文件)
- 四、用简单神经网络识别手写数字(内含代码详解及订正)
- WEB前端开发之ES6(1)
- 在PyCharm中安装第三方库
- 日志分析查看——grep,sed,sort,awk运用
- 九度oj-1023:Excel排序
- CSDN博客去除烦人的“收藏到代码笔记”
- NYOJ 138 找球号(二)