您的位置:首页 > 其它

LeetCode 110. Balanced Binary Tree (平衡二叉树)

2017-07-04 00:36 483 查看

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.

 

题目标签:Tree

  这道题目给了我们一个 二叉树, 让我们来判断一下它是否是一个 height-balanced 二叉树。 先来看一下什么是 height-balanced 二叉树, 对于每一个点,它的左边子树的depth 和右边子树的 depth 不能相差多余1。这道题目可以利用getDepth 来帮助我们判断。getDepth function 是通过递归,利用postOrder来从树的最低端走起,当点是null时候,就返回depth 0, 每次返回depth + 1, 那么我们可以多加一个if statement 在 一个parent 点拿到左边的depth 和右边的depth 之后, 如果左边和右边的相差值,大于1,那么 把我们预先设的 boolean is_balanced 改为false。

 

Java Solution:

Runtime beats 25.84% 

完成日期:07/03/2017

关键词:Tree

关键点:利用 getDepth function

 

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

public boolean isBalanced(TreeNode root)
{
getDepth(root);

return is_balanced;
}

public int getDepth(TreeNode node)
{
if(node == null)
return 0;

int left_depth = getDepth(node.left);
int right_depth = getDepth(node.right);

if(Math.abs(left_depth - right_depth) > 1)
is_balanced = false;

return Math.max(left_depth, right_depth) + 1;
}
}

参考资料:N/A

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: