美文网首页
110.平衡二叉树

110.平衡二叉树

作者: 皮蛋豆腐酱油 | 来源:发表于2019-06-03 14:30 被阅读0次

给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null) {
            return true;
        }
        int leftDepth = treeDepth(root.left);
        int rightDepth = treeDepth(root.right);     
        int num = Math.abs(leftDepth - rightDepth);
        if(num > 1) {
            return false;
        } else {
            return isBalanced(root.left) && isBalanced(root.right);
        }
    }
    int dep = 0;
    public static int treeDepth(TreeNode root){
        if(root == null){
            return 0;
        }
        int left = treeDepth(root.left);
        int right = treeDepth(root.right);
        
        return (left>right)?(left+1):(right+1);
    }
}

相关文章

网友评论

      本文标题:110.平衡二叉树

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