设为首页 加入收藏

TOP

二叉树高度的平衡标准
2013-12-05 13:05:50 来源: 作者: 【 】 浏览:164
Tags:高度 平衡 标准
    题目 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
    其次,理解题目后,很容易想到这是一道典型的递归题目(ps:特别是面试的时候,二叉树和递归联系的特别多,我面试豌豆荚也是考了一个类似的题目)
    最后,首先判断根节点的左右子树高度差,相差大于1返回false,相差不大于1则继续递归的测试根节点的左子树和右子树
    AC代码
    public class BalancedBinaryTree {
    static class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int x) {
    this.val = x;
    }
    }
    public static boolean isBalanced(TreeNode root) {
    if (root == null) return true;
    int lh = getHeight(root.left);
    int rh = getHeight(root.right);
    if (Math.abs(lh - rh) > 1) return false;
    return isBalanced(root.left) && isBalanced(root.right);
    }
    public static int getHeight(TreeNode root) {
    if (root == null) return 0;
    return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
    }
    }
    吐槽 csdn神马时候才能支持markdown语法编辑博客啊,如果到过年还不支持markdown,果断迁移到segmentfault上了

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C++中静态初始化的相依性 下一篇二进制位最后出现1的概率

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·定义一个类模板并实 (2025-12-27 06:52:28)
·一文搞懂怎么用C语言 (2025-12-27 06:52:25)
·常用C模板范文_百度 (2025-12-27 06:52:21)
·【C语言】动态内存管 (2025-12-27 06:23:20)
·C语言中的内存管理 - (2025-12-27 06:23:16)