Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to check the balance of binary trees by LeetCode

Shulou Source: shulou.com Published: 2022-06-01 13:04:11 09月11日 Update

This article mainly shows you "LeetCode how to check the balance of binary trees". The content is simple and easy to understand, and the organization is clear. I hope it can help you solve your doubts. Let Xiaobian lead you to study and learn this article "LeetCode how to check the balance of binary trees".

1. Brief description of the problem

Implement a function to check whether the binary tree is balanced.

In this case, the balanced tree is defined as follows:

The height difference between two subtrees of any node does not exceed 1.

2, example

Example 1: Given binary tree [3,9,20,null,null,15,7] 3 / \ 9 20 / \ 15 7 returns true. Example 2: Given binary tree [1,2,2,3,3,null,null,4,4] 1 / \ 2 2 / \ 3 3 / \4 4 returns false.

3, the solution to the problem

solve recursively

4, the solution program

public class IsBalancedTest { public static void main(String[] args) { TreeNode t1 = new TreeNode(3); TreeNode t2 = new TreeNode(9); TreeNode t3 = new TreeNode(20); TreeNode t4 = new TreeNode(15); TreeNode t5 = new TreeNode(7); t1.left = t2; t1.right = t3; t3.left = t4; t3.right = t5; boolean balanced = isBalanced(t1); System.out.println("balanced = " + balanced);

}

public static boolean isBalanced(TreeNode root) { if (root == null) { return true; } int leftDepth = dfs(root.left); int rightDepth = dfs(root.right); int abs = Math.abs(leftDepth - rightDepth); if (abs

Tags: Check balance content examples articles problem solutions programs questions learning help functions pictures ideas ways easy to understand more organization knowledge editing nodes Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Microsoft OPPO Reno Linux Huawei