美文网首页
判断一棵树是不是平衡二叉树

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

作者: superczb | 来源:发表于2017-11-02 11:16 被阅读0次

    题目描述

    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;

    }

    }

    相关文章

      网友评论

          本文标题:判断一棵树是不是平衡二叉树

          本文链接:https://www.haomeiwen.com/subject/krjopxtx.html