您现在的位置是:首页 > 后台技术 > 数据结构与算法数据结构与算法
平衡二叉树(图文)
第十三双眼睛2023-11-27【数据结构与算法】人已围观
简介平衡二叉树
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
思路:要确定该二叉树是平衡二叉树,需要该二叉树的左子树和右子树的深度差小于等于1,并且,递归的每个节点的左子树和右子树的深度差不超过1。代码如下
public static boolean method1(TreeNode root) { if (root == null) { return true; } return Math.abs(test(root.left) - test(root.right)) > 1 && method1(root.left) && method1(root.right); } public static int test(TreeNode node) { if (node == null) { return 0; } return Math.max(test(node.left), test(node.right)) + 1; } |
Tags:
很赞哦! ()
下一篇:二叉树的最小深度(图文)