【leetcode】Balanced Binary Tree
2014-07-29 22:46
302 查看
题目:
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代码如下:
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; }
相关文章推荐
- Balanced Binary Tree -- LeetCode
- LeetCode:Balanced Binary Tree(判断是否为二叉平衡树)
- leetcode - 110. Balanced Binary Tree
- LeetCode(24)-Balanced Binary Tree
- Leetcode---Balanced Binary Tree
- LeetCode110. Balanced Binary Tree
- LeetCode:110. Balanced Binary Tree
- [leetcode] Balanced Binary Tree
- [LeetCode] Balanced Binary Tree 深度搜索
- leetcode 110. 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[110] Balanced Binary Tree
- [leetcode]Balanced Binary Tree