From 9a5dae5dfd7c92dbccce4ce73700056b0392abdb Mon Sep 17 00:00:00 2001 From: Omooo <869759698@qq.com> Date: Fri, 10 Jul 2020 09:31:56 +0800 Subject: [PATCH] =?UTF-8?q?Update=20=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9B=B8?= =?UTF-8?q?=E5=85=B3.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- blogs/Algorithm/剑指 Offer/二叉树相关.md | 56 ++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/blogs/Algorithm/剑指 Offer/二叉树相关.md b/blogs/Algorithm/剑指 Offer/二叉树相关.md index fb81591..0af2c92 100644 --- a/blogs/Algorithm/剑指 Offer/二叉树相关.md +++ b/blogs/Algorithm/剑指 Offer/二叉树相关.md @@ -236,3 +236,59 @@ class Solution { } ``` +#### [55 - II. 平衡二叉树](https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/) + +```java +class Solution { + + public boolean isBalanced(TreeNode root) { + if (root == null) { + return true; + } + Deque queue = new LinkedList<>(); + queue.add(root); + while (!queue.isEmpty()) { + TreeNode node = queue.poll(); + int offset = Math.abs(maxDepth(node.left) - maxDepth(node.right)); + if (offset > 1) { + return false; + } + if (node.left != null) { + queue.add(node.left); + } + if (node.right != null) { + queue.add(node.right); + } + } + return true; + } + + private int maxDepth(TreeNode root) { + if (root == null) { + return 0; + } + return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; + } +} +``` + +```java +class Solution { + + public boolean isBalanced(TreeNode root) { + if (root == null) { + return true; + } + return Math.abs(maxDepth(root.left) - maxDepth(root.right)) <= 1 && isBalanced(root.left) && isBalanced( + root.right); + } + + private int maxDepth(TreeNode root) { + if (root == null) { + return 0; + } + return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; + } +} +``` +