Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 95be04b

Browse files
author
guangsheng.li01
committed
Solved 0654
1 parent 71e4dec commit 95be04b

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

‎src/a0654_maximum_binary_tree.rs

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/*
2+
* [0654] maximum-binary-tree
3+
*/
4+
5+
use super::utils::tree::*;
6+
pub struct Solution {}
7+
8+
// solution impl starts here
9+
10+
// Definition for a binary tree node.
11+
// #[derive(Debug, PartialEq, Eq)]
12+
// pub struct TreeNode {
13+
// pub val: i32,
14+
// pub left: Option<Rc<RefCell<TreeNode>>>,
15+
// pub right: Option<Rc<RefCell<TreeNode>>>,
16+
// }
17+
//
18+
// impl TreeNode {
19+
// #[inline]
20+
// pub fn new(val: i32) -> Self {
21+
// TreeNode {
22+
// val,
23+
// left: None,
24+
// right: None
25+
// }
26+
// }
27+
// }
28+
use std::cell::RefCell;
29+
use std::rc::Rc;
30+
impl Solution {
31+
pub fn construct_maximum_binary_tree(nums: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
32+
if nums.len() == 0 {
33+
return Option::None;
34+
}
35+
36+
let mut i = 0;
37+
for j in 0..nums.len() {
38+
if nums[j] > nums[i] {
39+
i = j;
40+
}
41+
}
42+
43+
let left = Self::construct_maximum_binary_tree(nums[..i].to_vec());
44+
let right = Self::construct_maximum_binary_tree(nums[i + 1..].to_vec());
45+
46+
Some(Rc::new(RefCell::new(TreeNode {
47+
val: nums[i],
48+
left: left,
49+
right: right,
50+
})))
51+
}
52+
}
53+
// solution impl ends here
54+
55+
// solution tests starts here
56+
57+
#[cfg(test)]
58+
mod tests {
59+
use super::*;
60+
61+
#[test]
62+
fn test_case0() {
63+
assert_eq!(
64+
Solution::construct_maximum_binary_tree(vec![3, 2, 1, 6, 0, 5]),
65+
tree![6, 3, 5, null, 2, 0, null, null, 1]
66+
);
67+
}
68+
}
69+
70+
// solution tests ends here

‎src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ mod a0405_convert_a_number_to_hexadecimal;
3131
mod a0617_merge_two_binary_trees;
3232
mod a0643_maximum_average_subarray_i;
3333
mod a0646_maximum_length_of_pair_chain;
34+
mod a0654_maximum_binary_tree;
3435
mod a0867_transpose_matrix;
3536
mod a0883_projection_area_of_3d_shapes;
3637
mod a0929_unique_email_addresses;

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /