From cd5996c825bc7f18ad34f69bfa1511991f20859a Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Wed, 23 Nov 2022 06:08:06 -0500 Subject: [PATCH 1/2] =?UTF-8?q?Update=200654.=E6=9C=80=E5=A4=A7=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/0654.最大二叉树.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0654.最大二叉树.md b/problems/0654.最大二叉树.md index fda64372..667610d8 100644 --- a/problems/0654.最大二叉树.md +++ b/problems/0654.最大二叉树.md @@ -509,6 +509,34 @@ object Solution { } ``` +### Rust + +```rust +use std::cell::RefCell; +use std::rc::Rc; +impl Solution { + pub fn construct_maximum_binary_tree(nums: Vec) -> Option>> { + Self::traversal(&nums, 0, nums.len()) + } + + pub fn traversal(nums: &Vec, left: usize, right: usize) -> Option>> { + if left >= right { + return None; + } + let mut max_value_index = left; + for i in left + 1..right { + if nums[max_value_index] < nums[i] { + max_value_index = i; + } + } + let mut root = TreeNode::new(nums[max_value_index]); + root.left = Self::traversal(nums, left, max_value_index); + root.right = Self::traversal(nums, max_value_index + 1, right); + Some(Rc::new(RefCell::new(root))) + } +} +``` +

From fc4dec09d3d3aad240f23d360e7f8ee075eb7d67 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sat, 26 Nov 2022 01:51:11 +0800 Subject: [PATCH 2/2] =?UTF-8?q?Update=200654.=E6=9C=80=E5=A4=A7=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/0654.最大二叉树.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/problems/0654.最大二叉树.md b/problems/0654.最大二叉树.md index 667610d8..f1837216 100644 --- a/problems/0654.最大二叉树.md +++ b/problems/0654.最大二叉树.md @@ -511,6 +511,35 @@ object Solution { ### Rust +新建数组: + +```rust +use std::cell::RefCell; +use std::rc::Rc; +impl Solution{ + pub fn construct_maximum_binary_tree(mut nums: Vec) -> Option>> { + if nums.is_empty() { + return None; + } + let mut max_value_index = 0; + for i in 0..nums.len() { + if nums[max_value_index] < nums[i] { + max_value_index = i; + } + } + let right = Self::construct_maximum_binary_tree(nums.split_off(max_value_index + 1)); + let root = nums.pop().unwrap(); + let left = Self::construct_maximum_binary_tree(nums); + Some(Rc::new(RefCell::new(TreeNode { + val: root, + left, + right, + }))) + } +} +``` + +数组索引: ```rust use std::cell::RefCell; use std::rc::Rc;