root 노드의 왼쪽 Subtree와 오른쪽 Subtree의 높이의 차이가 1이하인 경우 Tree가 균형잡혀있다고 할 수 있으므로, 각 Subtree의 최대 깊이와 최소 깊이를 구하여 그 차이를 구한다.
/*
 * pseudo code: need more elaboration to run
*/
    public static int maxDepth( Node root ) {
        if( root==null )
            return 1;
        return (1 + Math.max( maxDepth(root.getLeft()), maxDepth(root.getRight()) );
    }
    public static int minDepth( Node root ) {
        if( root==null )
            return 1;
        return (1 + Math.min( minDepth(root.getLeft()), minDepth(root.getRight()) );
    }
    public static boolean isBalanced( Node root ) {
        int nMax = maxDepth( roor );
        int nMin = minDepth( roor );
        if( (nMax-nMin)>1 )
            System.out.println( "Not balanced" );
        else
             System.out.println( "Balanced" );
    }
 
댓글 없음:
댓글 쓰기