设为首页 加入收藏

TOP

LeetCode-Balanced Binary Tree
2015-07-20 17:44:13 来源: 作者: 【 】 浏览:1
Tags:LeetCode-Balanced Binary Tree

?

?

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.

源码Java版本
算法分析:使用栈。时间复杂度O(n),空间复杂度O(logn)

?

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isBalanced(TreeNode root) {
        return balancedHeight(root)>=0?true:false;
    }
    
    private int balancedHeight(TreeNode root) {
        if(root==null) {
            return 0;
        }
        int left=balancedHeight(root.left);
        int right=balancedHeight(root.right);
        
        if(left<0 || right <0 || Math.abs(left-right)>1) {
            return -1;
        }
        return Math.max(left,right)+1;
    }
}

?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Leetcode 栈 Valid Parentheses 下一篇LeetCode-Binary Tree Inorder Tr..

评论

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

·常用meta整理 | 菜鸟 (2025-12-25 01:21:52)
·SQL HAVING 子句:深 (2025-12-25 01:21:47)
·SQL CREATE INDEX 语 (2025-12-25 01:21:45)
·Shell 传递参数 (2025-12-25 00:50:45)
·Linux echo 命令 - (2025-12-25 00:50:43)