Skip to content

Commit

Permalink
Merge pull request youngyangyang04#1774 from fwqaaq/patch-24
Browse files Browse the repository at this point in the history
Update 0654.最大二叉树.md about rust
  • Loading branch information
youngyangyang04 authored Dec 15, 2022
2 parents d9577b4 + fc4dec0 commit 780ca66
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions problems/0654.最大二叉树.md
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,63 @@ object Solution {
}
```

### Rust

新建数组:

```rust
use std::cell::RefCell;
use std::rc::Rc;
impl Solution{
pub fn construct_maximum_binary_tree(mut nums: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
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;
impl Solution {
pub fn construct_maximum_binary_tree(nums: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
Self::traversal(&nums, 0, nums.len())
}

pub fn traversal(nums: &Vec<i32>, left: usize, right: usize) -> Option<Rc<RefCell<TreeNode>>> {
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)))
}
}
```

<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
Expand Down

0 comments on commit 780ca66

Please sign in to comment.