110. 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.

 

Hide Tags
  Tree Depth-first Search  

链接: http://leetcode.com/problems/balanced-binary-tree/

题解:

求一棵树是否是平衡树。根据定义计算两个子节点的深度,当深度差大于1时返回false,依然是DFS。

Time Complexity - O(n), Space Complexity - O(n)

public class Solution {

    public boolean isBalanced(TreeNode root) {

        return getDepth(root) != -1;

    }

    

    private int getDepth(TreeNode node){

        if(node == null)

            return 0;

        int leftDepth = getDepth(node.left);

        int rightDepth = getDepth(node.right);

        if(leftDepth  == -1 || rightDepth == -1 || Math.abs(leftDepth - rightDepth) > 1)

            return -1;

        return 1 + Math.max(leftDepth, rightDepth);

    }

}

测试:

你可能感兴趣的:(binary)