From 1af721e1ed561764b081c8d8ddc25d7c614fe7fd Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Tue, 15 Nov 2022 21:58:16 +0800 Subject: [PATCH] =?UTF-8?q?Update=200110.=E5=B9=B3=E8=A1=A1=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0110.平衡二叉树.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index 6e7c8c53..9751f2dd 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -810,6 +810,38 @@ func getHeight(_ root: TreeNode?) -> Int { } ``` +### rust + +递归 + +```rust +use std::cell::RefCell; +use std::rc::Rc; +impl Solution { + pub fn is_balanced(root: Option>>) -> bool { + Self::get_depth(root) != -1 + } + pub fn get_depth(root: Option>>) -> i32 { + if root.is_none() { + return 0; + } + let right = Self::get_depth(root.as_ref().unwrap().borrow().left.clone()); + let left = Self::get_depth(root.unwrap().borrow().right.clone()); + if right == -1 { + return -1; + } + if left == -1 { + return -1; + } + if (right - left).abs() > 1 { + return -1; + } + + 1 + right.max(left) + } +} +``` +