How to determine if binary tree is balanced?

前端 未结 27 1515
萌比男神i
萌比男神i 2020-11-30 16:11

It\'s been a while from those school years. Got a job as IT specialist at a hospital. Trying to move to do some actual programming now. I\'m working on binary trees now, a

27条回答
  •  长情又很酷
    2020-11-30 17:07

    public boolean isBalanced(TreeNode root)
    {
        return (maxDepth(root) - minDepth(root) <= 1);
    }
    
    public int maxDepth(TreeNode root)
    {
        if (root == null) return 0;
    
        return 1 + max(maxDepth(root.left), maxDepth(root.right));
    }
    
    public int minDepth (TreeNode root)
    {
        if (root == null) return 0;
    
        return 1 + min(minDepth(root.left), minDepth(root.right));
    }
    

提交回复
热议问题