LeetCode-Balanced Binary Tree
来源:互联网 发布:中宏产业数据库 编辑:程序博客网 时间:2024/05/22 21:18
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.
关于平衡二叉树,一下是百度百科给出的说明:
平衡二叉树(Balanced Binary Tree)又被称为AVL树(有别于AVL算法),且具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。平衡二叉树的常用实现方法有红黑树、AVL、替罪羊树、Treap、伸展树等。 最小二叉平衡树的节点的公式如下 F(n)=F(n-1)+F(n-2)+1 这个类似于一个递归的数列,可以参考Fibonacci(斐波那契)数列,1是根节点,F(n-1)是左子树的节点数量,F(n-2)是右子树的节点数量。
伪代码:
IsHeightBalanced(tree) return (tree is empty) or (IsHeightBalanced(tree.left) and IsHeightBalanced(tree.right) and abs(Height(tree.left) - Height(tree.right)) <= 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) { return maxDepth(root) !=-1; } public int maxDepth(TreeNode root){ if(root == null) return 0; //树为空树,返回,此时为平衡二叉树 int left = maxDepth(root.left); int right = maxDepth(root.right); if(left == -1 || right == -1 ||Math.abs(left-right) > 1) return -1; return Math.max(left,right) + 1; }}
0 0
- LeetCode: Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- LeetCode Balanced Binary Tree
- [Leetcode] Balanced Binary Tree
- LeetCode : Balanced Binary Tree
- LeetCode Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- 【leetcode】Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- [Leetcode]Balanced Binary Tree
- [leetcode]Balanced Binary Tree
- Leetcode: Balanced Binary Tree
- LeetCode-Balanced Binary Tree
- LeetCode - Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- LeetCode | Balanced Binary Tree
- 【leetcode】Balanced Binary Tree
- Spark MLlib聚类clustering:KMeans K均值 ---原理及实战
- 伯乐在线
- 信息隐藏课程之索引图像的隐写
- 确定字符互异
- PAT_乙级 1011 A+B和C
- LeetCode-Balanced Binary Tree
- Spring基础:快速入门spring(4):setter注入
- 模式识别五--PCA主分量分析与Fisher线性判别
- C语言题目
- 模式识别六--感知器的实现
- git svn
- 模拟退火算法求函数最小值问题的C/C++实现
- 2016.11.26
- 【ASP.NET】ADO.NET