Skip to content

Commit f6dc945

Browse files
author
joker53-1
committed
first
1 parent bc55636 commit f6dc945

8 files changed

+641
-0
lines changed

src/problem/mod.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,10 @@ mod p0094_binary_tree_inorder_traversal;
1111
mod p0095_unique_binary_search_trees_ii;
1212
mod p0096_unique_binary_search_trees;
1313
mod p0098_validate_binary_search_tree;
14+
mod p0099_recover_binary_search_tree;
15+
mod p0100_same_tree;
16+
mod p0101_symmetric_tree;
17+
mod p0102_binary_tree_level_order_traversal;
18+
mod p0103_binary_tree_zigzag_level_order_traversal;
19+
mod p0104_maximum_depth_of_binary_tree;
20+
mod p0105_construct_binary_tree_from_preorder_and_inorder_traversal;
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
/**
2+
* [99] Recover Binary Search Tree
3+
*
4+
* You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.
5+
*
6+
* <strong class="example">Example 1:
7+
* <img alt="" src="https://assets.leetcode.com/uploads/2020/10/28/recover1.jpg" style="width: 422px; height: 302px;" />
8+
* Input: root = [1,3,null,null,2]
9+
* Output: [3,1,null,null,2]
10+
* Explanation: 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid.
11+
*
12+
* <strong class="example">Example 2:
13+
* <img alt="" src="https://assets.leetcode.com/uploads/2020/10/28/recover2.jpg" style="width: 581px; height: 302px;" />
14+
* Input: root = [3,1,4,null,null,2]
15+
* Output: [2,1,4,null,null,3]
16+
* Explanation: 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid.
17+
*
18+
*
19+
* Constraints:
20+
*
21+
* The number of nodes in the tree is in the range [2, 1000].
22+
* -2^31 <= Node.val <= 2^31 - 1
23+
*
24+
*
25+
* Follow up: A solution using O(n) space is pretty straight-forward. Could you devise a constant O(1) space solution?
26+
*/
27+
pub struct Solution {}
28+
use crate::util::tree::{TreeNode, to_tree};
29+
30+
// problem: https://leetcode.com/problems/recover-binary-search-tree/
31+
// discuss: https://leetcode.com/problems/recover-binary-search-tree/discuss/?currentPage=1&orderBy=most_votes&query=
32+
33+
// submission codes start here
34+
35+
// Definition for a binary tree node.
36+
// #[derive(Debug, PartialEq, Eq)]
37+
// pub struct TreeNode {
38+
// pub val: i32,
39+
// pub left: Option<Rc<RefCell<TreeNode>>>,
40+
// pub right: Option<Rc<RefCell<TreeNode>>>,
41+
// }
42+
//
43+
// impl TreeNode {
44+
// #[inline]
45+
// pub fn new(val: i32) -> Self {
46+
// TreeNode {
47+
// val,
48+
// left: None,
49+
// right: None
50+
// }
51+
// }
52+
// }
53+
use std::rc::Rc;
54+
use std::cell::RefCell;
55+
impl Solution {
56+
pub fn recover_tree(root: &mut Option<Rc<RefCell<TreeNode>>>) {
57+
let mut res = vec![];
58+
Self::dfs(root, &mut res);
59+
let (mut x, mut y) = (None, None);
60+
for i in 0..res.len()-1 {
61+
if res[i+1] < res[i] {
62+
y = Some(res[i+1]);
63+
if x == None {
64+
x = Some(res[i]);
65+
}
66+
}
67+
}
68+
Self::recover_tree2(root, x.unwrap(), y.unwrap());
69+
}
70+
71+
fn dfs(node: &Option<Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
72+
if let Some(node) = node {
73+
Self::dfs(&node.borrow().left, res);
74+
res.push(node.borrow().val);
75+
Self::dfs(&node.borrow().right, res);
76+
}
77+
}
78+
79+
fn recover_tree2(root: &mut Option<Rc<RefCell<TreeNode>>>, x: i32, y: i32) {
80+
if let Some(node) = root {
81+
Self::recover_tree2(&mut node.borrow_mut().left, x, y);
82+
if node.borrow().val == x || node.borrow().val == y {
83+
node.borrow_mut().val = if node.borrow().val == x { y } else { x };
84+
}
85+
Self::recover_tree2(&mut node.borrow_mut().right, x, y);
86+
}
87+
}
88+
}
89+
90+
// submission codes end
91+
92+
#[cfg(test)]
93+
mod tests {
94+
use super::*;
95+
96+
#[test]
97+
fn test_99() {
98+
}
99+
}

src/problem/p0100_same_tree.rs

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/**
2+
* [100] Same Tree
3+
*
4+
* Given the roots of two binary trees p and q, write a function to check if they are the same or not.
5+
* Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
6+
*
7+
* <strong class="example">Example 1:
8+
* <img alt="" src="https://assets.leetcode.com/uploads/2020/12/20/ex1.jpg" style="width: 622px; height: 182px;" />
9+
* Input: p = [1,2,3], q = [1,2,3]
10+
* Output: true
11+
*
12+
* <strong class="example">Example 2:
13+
* <img alt="" src="https://assets.leetcode.com/uploads/2020/12/20/ex2.jpg" style="width: 382px; height: 182px;" />
14+
* Input: p = [1,2], q = [1,null,2]
15+
* Output: false
16+
*
17+
* <strong class="example">Example 3:
18+
* <img alt="" src="https://assets.leetcode.com/uploads/2020/12/20/ex3.jpg" style="width: 622px; height: 182px;" />
19+
* Input: p = [1,2,1], q = [1,1,2]
20+
* Output: false
21+
*
22+
*
23+
* Constraints:
24+
*
25+
* The number of nodes in both trees is in the range [0, 100].
26+
* -10^4 <= Node.val <= 10^4
27+
*
28+
*/
29+
pub struct Solution {}
30+
use crate::util::tree::{TreeNode, to_tree};
31+
32+
// problem: https://leetcode.com/problems/same-tree/
33+
// discuss: https://leetcode.com/problems/same-tree/discuss/?currentPage=1&orderBy=most_votes&query=
34+
35+
// submission codes start here
36+
37+
// Definition for a binary tree node.
38+
// #[derive(Debug, PartialEq, Eq)]
39+
// pub struct TreeNode {
40+
// pub val: i32,
41+
// pub left: Option<Rc<RefCell<TreeNode>>>,
42+
// pub right: Option<Rc<RefCell<TreeNode>>>,
43+
// }
44+
//
45+
// impl TreeNode {
46+
// #[inline]
47+
// pub fn new(val: i32) -> Self {
48+
// TreeNode {
49+
// val,
50+
// left: None,
51+
// right: None
52+
// }
53+
// }
54+
// }
55+
use std::rc::Rc;
56+
use std::cell::RefCell;
57+
impl Solution {
58+
pub fn is_same_tree(p: Option<Rc<RefCell<TreeNode>>>, q: Option<Rc<RefCell<TreeNode>>>) -> bool {
59+
if p.is_none() && q.is_none() { return true; }
60+
if (p.is_none() && q.is_some()) || (p.is_some() && q.is_none()) { return false; }
61+
Self::is_same_tree(p.as_ref().unwrap().borrow().left.clone(), q.as_ref().unwrap().borrow().left.clone()) && Self::is_same_tree(p.as_ref().unwrap().borrow().right.clone(), q.as_ref().unwrap().borrow().right.clone()) && p.unwrap().borrow().val == q.unwrap().borrow().val
62+
}
63+
}
64+
65+
// submission codes end
66+
67+
#[cfg(test)]
68+
mod tests {
69+
use super::*;
70+
71+
#[test]
72+
fn test_100() {
73+
}
74+
}
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/**
2+
* [101] Symmetric Tree
3+
*
4+
* Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
5+
*
6+
* <strong class="example">Example 1:
7+
* <img alt="" src="https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg" style="width: 354px; height: 291px;" />
8+
* Input: root = [1,2,2,3,4,4,3]
9+
* Output: true
10+
*
11+
* <strong class="example">Example 2:
12+
* <img alt="" src="https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg" style="width: 308px; height: 258px;" />
13+
* Input: root = [1,2,2,null,3,null,3]
14+
* Output: false
15+
*
16+
*
17+
* Constraints:
18+
*
19+
* The number of nodes in the tree is in the range [1, 1000].
20+
* -100 <= Node.val <= 100
21+
*
22+
*
23+
* Follow up: Could you solve it both recursively and iteratively?
24+
*/
25+
pub struct Solution {}
26+
use crate::util::tree::{TreeNode, to_tree};
27+
28+
// problem: https://leetcode.com/problems/symmetric-tree/
29+
// discuss: https://leetcode.com/problems/symmetric-tree/discuss/?currentPage=1&orderBy=most_votes&query=
30+
31+
// submission codes start here
32+
33+
// Definition for a binary tree node.
34+
// #[derive(Debug, PartialEq, Eq)]
35+
// pub struct TreeNode {
36+
// pub val: i32,
37+
// pub left: Option<Rc<RefCell<TreeNode>>>,
38+
// pub right: Option<Rc<RefCell<TreeNode>>>,
39+
// }
40+
//
41+
// impl TreeNode {
42+
// #[inline]
43+
// pub fn new(val: i32) -> Self {
44+
// TreeNode {
45+
// val,
46+
// left: None,
47+
// right: None
48+
// }
49+
// }
50+
// }
51+
use std::rc::Rc;
52+
use std::cell::RefCell;
53+
impl Solution {
54+
pub fn is_symmetric(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
55+
if root.is_none() { return true; }
56+
Self::is_same_tree(root.as_ref().unwrap().borrow().left.clone(), root.as_ref().unwrap().borrow().right.clone())
57+
}
58+
59+
fn is_same_tree(p: Option<Rc<RefCell<TreeNode>>>, q: Option<Rc<RefCell<TreeNode>>>) -> bool {
60+
if p.is_none() && q.is_none() { return true; }
61+
if (p.is_none() && q.is_some()) || (p.is_some() && q.is_none()) { return false; }
62+
Self::is_same_tree(p.as_ref().unwrap().borrow().left.clone(), q.as_ref().unwrap().borrow().right.clone()) && Self::is_same_tree(p.as_ref().unwrap().borrow().right.clone(), q.as_ref().unwrap().borrow().left.clone()) && p.unwrap().borrow().val == q.unwrap().borrow().val
63+
}
64+
}
65+
66+
// submission codes end
67+
68+
#[cfg(test)]
69+
mod tests {
70+
use super::*;
71+
72+
#[test]
73+
fn test_101() {
74+
}
75+
}
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
/**
2+
* [102] Binary Tree Level Order Traversal
3+
*
4+
* Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).
5+
*
6+
* <strong class="example">Example 1:
7+
* <img alt="" src="https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg" style="width: 277px; height: 302px;" />
8+
* Input: root = [3,9,20,null,null,15,7]
9+
* Output: [[3],[9,20],[15,7]]
10+
*
11+
* <strong class="example">Example 2:
12+
*
13+
* Input: root = [1]
14+
* Output: [[1]]
15+
*
16+
* <strong class="example">Example 3:
17+
*
18+
* Input: root = []
19+
* Output: []
20+
*
21+
*
22+
* Constraints:
23+
*
24+
* The number of nodes in the tree is in the range [0, 2000].
25+
* -1000 <= Node.val <= 1000
26+
*
27+
*/
28+
pub struct Solution {}
29+
use crate::util::tree::{TreeNode, to_tree};
30+
31+
// problem: https://leetcode.com/problems/binary-tree-level-order-traversal/
32+
// discuss: https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/?currentPage=1&orderBy=most_votes&query=
33+
34+
// submission codes start here
35+
36+
// Definition for a binary tree node.
37+
// #[derive(Debug, PartialEq, Eq)]
38+
// pub struct TreeNode {
39+
// pub val: i32,
40+
// pub left: Option<Rc<RefCell<TreeNode>>>,
41+
// pub right: Option<Rc<RefCell<TreeNode>>>,
42+
// }
43+
//
44+
// impl TreeNode {
45+
// #[inline]
46+
// pub fn new(val: i32) -> Self {
47+
// TreeNode {
48+
// val,
49+
// left: None,
50+
// right: None
51+
// }
52+
// }
53+
// }
54+
use std::rc::Rc;
55+
use std::cell::RefCell;
56+
use std::collections::VecDeque;
57+
58+
impl Solution {
59+
pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
60+
// if root.is_none() { return vec![]; }
61+
// let mut q = VecDeque::new();
62+
// q.push_back(root);
63+
// let mut res = Vec::new();
64+
// while !q.is_empty() {
65+
// let len = q.len();
66+
// let mut level = Vec::new();
67+
// for _ in 0..len {
68+
// if let Some(node) = q.pop_front() {
69+
// if let Some(c) = node {
70+
// q.push_back(c.borrow().left.clone());
71+
// q.push_back(c.borrow().right.clone());
72+
// level.push(c.borrow().val);
73+
// }
74+
// }
75+
// }
76+
// if !level.is_empty() {
77+
// res.push(level);
78+
// }
79+
// }
80+
// res
81+
82+
let root = match root {
83+
Some(node) => node,
84+
None => return Vec::new(),
85+
};
86+
87+
let mut queue = VecDeque::new();
88+
queue.push_back(root);
89+
let mut result = Vec::new();
90+
91+
while !queue.is_empty() {
92+
let level_size = queue.len();
93+
let mut current_level = Vec::with_capacity(level_size);
94+
95+
for _ in 0..level_size {
96+
let node = queue.pop_front().unwrap();
97+
98+
// 只借用一次
99+
{
100+
let node_ref = node.borrow();
101+
current_level.push(node_ref.val);
102+
103+
if let Some(left) = node_ref.left.as_ref() {
104+
queue.push_back(Rc::clone(left));
105+
}
106+
if let Some(right) = node_ref.right.as_ref() {
107+
queue.push_back(Rc::clone(right));
108+
}
109+
} // 借用在这里结束
110+
}
111+
112+
result.push(current_level);
113+
}
114+
115+
result
116+
}
117+
}
118+
119+
// submission codes end
120+
121+
#[cfg(test)]
122+
mod tests {
123+
use super::*;
124+
125+
#[test]
126+
fn test_102() {
127+
}
128+
}

0 commit comments

Comments
 (0)