Trees

Balanced Binary Tree

Estimated reading: 1 minute 35 views

height-balanced binary tree is defined as a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

				
					 public boolean isBalanced(TreeNode root) {
        return dfs(root)[0] == 1;
    }

    private int[] dfs(TreeNode root) {
        if (root == null) {
            return new int[]{1, 0};
        }

        int[] left = dfs(root.left);
        int[] right = dfs(root.right);

        boolean balanced = left[0] == 1 && right[0] == 1 && Math.abs(left[1] - right[1]) <= 1;
        int height = 1 + Math.max(left[1], right[1]);

        return new int[]{balanced ? 1 : 0, height};
    }
				
			
Share this Doc

Balanced Binary Tree

Or copy link

CONTENTS