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

判断是否为一个平衡二叉树,及=即判断它是否为一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

两个递归函数,一个判断当前结点左右子树的高度差,另一个求当前结点的子树高度,代码如下:

public class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null) return true;
        System.out.println("LeftHeight:" + getHeight(root));
        if(Math.abs(getHeight(root.left) - getHeight(root.right)) <= 1)
            return isBalanced(root.left) && isBalanced(root.right);
        return false;
    }

    public int getHeight(TreeNode root){
        if(root == null) return 0;
        return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
    }
}

感觉通过一段时间在leetcode上的练习写递归时的思路越来越清晰了,代码也比当初简洁了不少。

题目链接:https://leetcode.com/problems/balanced-binary-tree/

你可能感兴趣的:(LeetCode)