How to determine if binary tree is balanced?

前端 未结 27 1518
萌比男神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 16:52

    Post order solution, traverse the tree only once. Time complexity is O(n), space is O(1), it's better than top-down solution. I give you a java version implementation.

    public static  boolean isBalanced(TreeNode root){
        return checkBalance(root) != -1;
    }
    
    private static  int checkBalance(TreeNode node){
        if(node == null) return 0;
        int left = checkBalance(node.getLeft());
    
        if(left == -1) return -1;
    
        int right = checkBalance(node.getRight());
    
        if(right == -1) return -1;
    
        if(Math.abs(left - right) > 1){
            return -1;
        }else{
            return 1 + Math.max(left, right);
        }
    }
    

提交回复
热议问题