算法9:LeetCode_给定一个二叉树,判断它是否是高度平衡的二叉树。
我们在算法7中已经学习了二叉排序树,平衡二叉树的相关知识。既然我们知道平衡二叉树中,节点的左子树和右子树的高度差至多为1,那么我们就可以通过如下思路来进行判断。
1. 节点的左节点值小于根节点的值
2. 节点的右节点值大于根节点的值
3. 节点左右子树的高度差至多为1.
本体是Leetcode原题 https://leetcode.cn/problems/binary-tree-level-order-traversal-ii/,根据给定的事例我们知道,本题中判断一棵树是否是高度平衡,并不是说判断这棵树是否是平衡二叉树。此题中,我们只关注这棵树中的左节点和右节点的高度差,并不关注左节点和有节点的值谁大,这和平衡二叉树是有区别的。
package code.code_04; /** * https://leetcode.cn/problems/balanced-binary-tree/ * 给定一个二叉树,判断它是否是高度平衡的二叉树。 * * 本题中,一棵高度平衡二叉树定义为: * * 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。 */ public class Code02_BalanceBinaryTree { public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } } public static class Info { public boolean isBalanced; public int height; public Info(boolean i, int h) { isBalanced = i; height = h; } } public boolean isBalanced(TreeNode root) { return process(root).isBalanced; } public static Info process(TreeNode root) { //边界值 if (root == null) { return new Info(true, 0); } Info leftInfo = process(root.left); Info rightInfo = process(root.right); //当前节点的高度 int height = Math.max(leftInfo.height, rightInfo.height) + 1; boolean isBalanced = leftInfo.isBalanced && rightInfo.isBalanced && Math.abs(leftInfo.height - rightInfo.height) < 2; return new Info(isBalanced, height); } public static void main(String[] args) { Code02_BalanceBinaryTree tree = new Code02_BalanceBinaryTree(); TreeNode node1 = tree.new TreeNode(3); TreeNode left2 = tree.new TreeNode(9); TreeNode righ2 = tree.new TreeNode(20); node1.left = left2; node1.right = righ2; TreeNode left3 = tree.new TreeNode(15); TreeNode righ3 = tree.new TreeNode(7); righ2.left = left3; righ2.right = righ3; System.out.println(tree.isBalanced(node1)); } }