【leetcode】Balanced Binary Tree

来源:互联网 发布:iphone蜂窝数据设置 编辑:程序博客网 时间:2024/06/05 15:48

题目:

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.


分析:该题要判断一棵二叉树是高度平衡的,平衡的条件是”对于任何一个节点,它的左右子树高度直插不超过1"。解法很显然是递归地判断每个节点是否满足高度平衡的要求,对于某个节点是否满足高度平衡,与三个因素有关:它的左子树是否高度平衡,它的右子树是否高度平衡,它的左右子树高度之差是否小于等于1。因此在递归的过程要传入两个参数:ifBalanced,该节点是否高度平衡,height,该节点的高度,可以定义内部类Node,包含以上变量。注意对于null节点,ifBalanced=true。


Java AC代码如下:

public boolean isBalanced(TreeNode root) {return cal(root).ifBalanced;}public Node cal(TreeNode root) {Node node = new Node();if (root == null) {node.height = 0;node.ifBalanced = true;return node;}node.left = cal(root.left);node.right = cal(root.right);node.height = Math.max(node.left.height, node.right.height) + 1;node.ifBalanced = (Math.abs(node.left.height - node.right.height) <= 1)&& node.left.ifBalanced && node.right.ifBalanced;return node;}class Node {boolean ifBalanced;int height;Node left;Node right;}


1 0
原创粉丝点击