判断一棵树是不是平衡二叉树

题目描述

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 ofeverynode never differ by more than 1.

我的思路:采用最笨的办法,递归的判断一棵树的左子树和右子树分别是不是平衡二叉树。


/**

* 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) {

if (root == null)

return true;

int ldepth = height(root.left);

int rdepth = height(root.right);

if (Math.abs(ldepth - rdepth) > 1)

return false;

boolean ltree = isBalanced(root.left);

boolean rtree = isBalanced(root.right);

return ltree & rtree;

}

public int height(TreeNode node){

if (node == null)

return 0;

int ldepth = height(node.left);

int rdepth = height(node.right);

return ldepth > rdepth?ldepth + 1:rdepth + 1;

}

}

你可能感兴趣的:(判断一棵树是不是平衡二叉树)