0
点赞
收藏
分享

微信扫一扫

【LeetCode】110. Balanced Binary Tree 平衡二叉树



文章目录


  • ​​题目描述​​
  • ​​解题方法​​

  • ​​方法一:递归​​
  • ​​方法二:递归+HashMap​​


  • ​​参考资料​​
  • ​​日期​​


[LeetCode]

​​https://leetcode.com/submissions/detail/40087813/​​

Total Accepted: 72203 Total Submissions: 225370 Difficulty: Easy

题目描述


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:

输入:root = [3,9,20,null,null,15,7]
输出:true

示例 2:

输入:root = [1,2,2,3,3,null,null,4,4]
输出:false
示例 3:

输入:root = []
输出:true

提示:


  • 树中的节点数在范围 [0, 5000] 内
  • -10^4 <= Node.val <= 10^4


解题方法

方法一:递归

运用递归,递归当前和 左子树和右子树的深度,当所有的左右子树的深度相差不超过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) {
if (root == null) {
return true;
}
int leftDepth = getDepth(root.left);
int rightDepth = getDepth(root.right);
return Math.abs(leftDepth - rightDepth) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
/**
* 递归方法计算树的高度
*
* @param root
* @return
*/
public static int getDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = getDepth(root.left);
int rightDepth = getDepth(root.right);
int treeDepth;
treeDepth = leftDepth > rightDepth ? leftDepth : rightDepth;
return treeDepth + 1;
}
}

方法二:递归+HashMap

上面的递归会对子树执行重复的深度计算,使用 HashMap 缓存每个子树的高度,能避免重复的高度计算。

每次计算树的深度的时候保存下来树的深度到一个HashMap里,下次寻找的时候先到 HashMap 里查找,找不到在进行计算,然后继续保存。优化算法后,是算法复杂度降到了O(n)。

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {

private static HashMap<TreeNode, Integer> nodeDepth = new HashMap<TreeNode, Integer>();


public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
int leftDepth = getDepth(root.left);
int rightDepth = getDepth(root.right);
return Math.abs(leftDepth - rightDepth) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
/**
* 递归方法计算树的高度
*
* @param root
* @return
*/
public static int getDepth(TreeNode root) {
if (root == null) {
nodeDepth.put(null, 0);
return 0;
}
if (nodeDepth.containsKey(root)) {
return nodeDepth.get(root);
}
int leftDepth = getDepth(root.left);
int rightDepth = getDepth(root.right);
int treeDepth;
treeDepth = (leftDepth > rightDepth ? leftDepth : rightDepth) + 1;
nodeDepth.put(root, treeDepth);
return treeDepth;
}
}


日期

2015/9/17 0:50:10



举报

相关推荐

0 条评论