资讯专栏INFORMATION COLUMN

[LintCode/LeetCode] Balanced Binary Tree

morgan / 1419人阅读

摘要:根据二叉平衡树的定义,我们先写一个求二叉树最大深度的函数。在主函数中,利用比较左右子树的差值来判断当前结点的平衡性,如果不满足则返回。

Problem

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.

Example

Given binary tree A={3,9,20,#,#,15,7}, B={3,#,20,15,7}

A)  3            B)    3 
   /                   
  9  20                 20
    /                  / 
   15   7              15  7

The binary tree A is a height-balanced binary tree, but B is not.

Note

根据二叉平衡树的定义,我们先写一个求二叉树最大深度的函数depth()。在主函数中,利用比较左右子树depth的差值来判断当前结点的平衡性,如果不满足则返回false。然后递归当前结点的左右子树,得到结果。

Solution
public class Solution {
    public boolean isBalanced(TreeNode root) {
        if (root == null) return true;
        if (Math.abs(depth(root.left)-depth(root.right)) > 1) return false;
        return isBalanced(root.left) && isBalanced(root.right);
    }
    public int depth(TreeNode root) {
        if (root == null) return 0;
        return Math.max(depth(root.left), depth(root.right))+1;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65851.html

相关文章

  • [LintCode/LeetCode] Binary Tree Pruning

    Problem Binary Tree PruningWe are given the head node root of a binary tree, where additionally every nodes value is either a 0 or a 1. Return the same tree where every subtree (of the given tree) not...

    rockswang 评论0 收藏0
  • [LintCode/LeetCode] Construct Binary Tree from Tr

    摘要:做了几道二分法的题目练手,发现这道题已经淡忘了,记录一下。这道题目的要点在于找的区间。边界条件需要注意若或数组为空,返回空当前进到超出末位,或超过,返回空每次创建完根节点之后,要将加,才能进行递归。 Construct Binary Tree from Inorder and Preorder Traversal Problem Given preorder and inorder t...

    马忠志 评论0 收藏0
  • [LintCode/LeetCode] Binary Tree Maximum Path Sum

    摘要:调用函数更新路径和的最大值,而函数本身需要递归,返回的是单边路径和。所以函数要返回的是,主函数中返回的却是最上一层根节点处和的较大值,与之前遍历过所有路径的最大值之间的最大值。 Problem Given a binary tree, find the maximum path sum. The path may start and end at any node in the tre...

    cnTomato 评论0 收藏0
  • [LintCode/LeetCode] Binary Tree Zigzag Level Orde

    Problem Given a binary tree, return the zigzag level order traversal of its nodes values. (ie, from left to right, then right to left for the next level and alternate between). Example Given binary tr...

    AlphaGooo 评论0 收藏0
  • [LintCode/LeetCode] Binary Tree InOrder Traversal

    摘要:递归法不说了,栈迭代的函数是利用的原理,从根节点到最底层的左子树,依次入堆栈。然后将出的结点值存入数组,并对出的结点的右子树用函数继续迭代。 Problem Given a binary tree, return the inorder traversal of its nodes values. Example Given binary tree {1,#,2,3}, 1 ...

    tomorrowwu 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<