树的几道题

This commit is contained in:
游由 2022-02-17 18:26:27 +08:00
parent 252fa11ebb
commit e2bc9efb04
6 changed files with 173 additions and 28 deletions

View File

@ -97,10 +97,12 @@ mod q0897;
mod q0912;
mod q0918;
mod q0938;
mod q0965;
mod q0977;
mod q0995;
mod q1006;
mod q1011;
mod q1022;
mod q1137;
mod q1143;
mod q1190;

View File

@ -65,7 +65,6 @@ mod test {
#[test]
fn test_q0110() {
let a = (|a: i32, b: i32| -> i32 { a + b })(1, 2);
let tree = Some(Rc::new(RefCell::new(TreeNode {
val: 3,
left: Some(Rc::new(RefCell::new(TreeNode::new(9)))),

View File

@ -32,18 +32,18 @@ impl Solution {
/// * 👎 0
pub fn binary_tree_paths(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<String> {
fn helper(root: &Option<Rc<RefCell<TreeNode>>>, mut path: Vec<i32>, ans: &mut Vec<String>) {
match root {
Some(node) => {
let p = node.borrow();
path.push(p.val);
if p.left.is_none() && p.right.is_none() {
ans.push(path.into_iter().map(|val| val.to_string()).collect::<Vec<String>>().join("->"));
} else {
if p.left.is_some() { helper(&p.left, path.clone(), ans); }
if p.right.is_some() { helper(&p.right, path.clone(), ans); }
if let Some(node) = root {
match node.borrow() {
p => {
path.push(p.val);
if p.left.is_none() && p.right.is_none() {
ans.push(path.into_iter().map(|val| val.to_string()).collect::<Vec<String>>().join("->"));
} else {
if p.left.is_some() { helper(&p.left, path.clone(), ans); }
if p.right.is_some() { helper(&p.right, path.clone(), ans); }
}
}
}
_ => {}
}
}
let mut ans = Vec::<String>::new();

View File

@ -29,26 +29,22 @@ impl Solution {
/// * 👍 392
/// * 👎 0
pub fn sum_of_left_leaves(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
fn is_leaf_node(node:&Option<Rc<RefCell<TreeNode>>>) -> bool {
let n = node.as_ref().unwrap().borrow();
n.left.is_none() && n.right.is_none()
}
let is_leaf_node = |node: &Option<Rc<RefCell<TreeNode>>>| -> bool { match node.as_ref().unwrap().borrow() { n => n.left.is_none() && n.right.is_none() } };
let mut ans = 0;
match root {
Some(node) => {
let mut p = node.borrow_mut();
if p.left.is_some() {
ans += if is_leaf_node(&p.left) {
p.left.as_ref().unwrap().borrow().val
} else {
Self::sum_of_left_leaves(p.left.take())
};
}
if p.right.is_some() && ! is_leaf_node(&p.right) {
ans += Self::sum_of_left_leaves(p.right.take());
if let Some(node) = root {
match node.borrow_mut() {
mut p => {
if p.left.is_some() {
ans += match is_leaf_node(&p.left) {
true => p.left.as_ref().unwrap().borrow().val,
_ => Self::sum_of_left_leaves(p.left.take())
}
}
if p.right.is_some() && !is_leaf_node(&p.right) {
ans += Self::sum_of_left_leaves(p.right.take());
}
}
}
_ => ()
}
ans
}

View File

@ -0,0 +1,68 @@
use crate::Solution;
use crate::structure::TreeNode;
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
/// [965.单值二叉树](https://leetcode-cn.com/problems/univalued-binary-tree/)
///
/// 2022-02-15 11:27:36
///
/// 如果二叉树每个节点都具有相同的值那么该二叉树就是_单值_二叉树。
///
/// 只有给定的树是单值二叉树时,才返回 `true`;否则返回 `false`。
///
/// + **示例 1**
/// + ![](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/29/screen-shot-2018-12-25-at-50104-pm.png)
/// + **输入:**\[1,1,1,1,1,null,1\]
/// + **输出:**true
/// + **示例 2**
/// + ![](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/29/screen-shot-2018-12-25-at-50050-pm.png)
/// + **输入:**\[2,2,2,5,2\]
/// + **输出:**false
/// + **提示:**
/// 1. 给定树的节点数范围是 `[1, 100]`。
/// 2. 每个节点的值都是整数,范围为 `[0, 99]` 。
/// + Related Topics
/// * 树
/// * 深度优先搜索
/// * 广度优先搜索
/// * 二叉树
/// * 👍 100
/// * 👎 0
pub fn is_unival_tree(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
match root {
Some(node) => match node.borrow_mut() {
mut p => (p.left.is_none() || p.val == p.left.as_ref().unwrap().borrow().val) && (p.right.is_none() || p.val == p.right.as_ref().unwrap().borrow().val) && Self::is_unival_tree(p.left.take()) && Self::is_unival_tree(p.right.take())
}
_ => true
}
}
}
#[cfg(test)]
mod test {
use crate::Solution;
use crate::structure::TreeNode;
use std::rc::Rc;
use std::cell::RefCell;
#[test]
fn test_q0965() {
let root = Some(Rc::new(RefCell::new(TreeNode{
val:1,
left:Some(Rc::new(RefCell::new(TreeNode{
val:1,
left:Some(Rc::new(RefCell::new(TreeNode::new(1)))),
right:Some(Rc::new(RefCell::new(TreeNode::new(1))))
}))),
right:Some(Rc::new(RefCell::new(TreeNode{
val:1,
left:Some(Rc::new(RefCell::new(TreeNode::new(1)))),
right:Some(Rc::new(RefCell::new(TreeNode::new(1))))
})))
})));
assert_eq!(Solution::is_unival_tree(root), true);
}
}

View File

@ -0,0 +1,80 @@
use crate::Solution;
use crate::structure::TreeNode;
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
/// [1022.从根到叶的二进制数之和](https://leetcode-cn.com/problems/sum-of-root-to-leaf-binary-numbers/)
///
/// 2022-02-15 11:20:32
///
/// 给出一棵二叉树,其上每个结点的值都是 `0` 或 `1` 。每一条从根到叶的路径都代表一个从最高有效位开始的二进制数。例如,如果路径为 `0 -> 1 -> 1 -> 0 -> 1`,那么它表示二进制数 `01101`,也就是 `13` 。
///
/// 对树上的每一片叶子,我们都要找出从根到该叶子的路径所表示的数字。
///
/// 返回这些数字之和。题目数据保证答案是一个 **32 位** 整数。
///
/// + **示例 1**
/// + ![](https://assets.leetcode.com/uploads/2019/04/04/sum-of-root-to-leaf-binary-numbers.png)
/// + **输入:** root = \[1,0,1,0,1,0,1\]
/// + **输出:** 22
/// + **解释:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
/// + **示例 2**
/// + **输入:** root = \[0\]
/// + **输出:** 0
/// + **示例 3**
/// + **输入:** root = \[1\]
/// + **输出:** 1
/// + **示例 4**
/// + **输入:** root = \[1,1\]
/// + **输出:** 3
/// + **提示:**
/// * 树中的结点数介于 `1` 和 `1000` 之间。
/// * `Node.val` 为 `0` 或 `1` 。
/// + Related Topics
/// * 树
/// * 深度优先搜索
/// * 二叉树
/// * 👍 136
/// * 👎 0
pub fn sum_root_to_leaf(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
fn helper(root: Option<Rc<RefCell<TreeNode>>>, val:i32) -> i32 {
match root {
Some(node) => match node.borrow_mut() {
mut p=> match p.right.is_none() && p.left.is_none() {
true => val | p.val,
_ => helper(p.left.take(), (val | p.val) << 1) + helper(p.right.take(), (val | p.val) << 1)
}
}
_ => 0
}
}
helper(root, 0)
}
}
#[cfg(test)]
mod test {
use crate::Solution;
use crate::structure::TreeNode;
use std::rc::Rc;
use std::cell::RefCell;
#[test]
fn test_q1022() {
let root = Some(Rc::new(RefCell::new(TreeNode{
val:1,
left:Some(Rc::new(RefCell::new(TreeNode{
val:0,
left:Some(Rc::new(RefCell::new(TreeNode::new(0)))),
right:Some(Rc::new(RefCell::new(TreeNode::new(1))))
}))),
right:Some(Rc::new(RefCell::new(TreeNode{
val:1,
left:Some(Rc::new(RefCell::new(TreeNode::new(0)))),
right:Some(Rc::new(RefCell::new(TreeNode::new(1))))
})))
})));
assert_eq!(Solution::sum_root_to_leaf(root), 22);
}
}