199. 二叉树的右视图
This commit is contained in:
+14
-13
@@ -3,28 +3,29 @@ mod tree;
|
||||
|
||||
use crate::tree::{TreeNode, build_tree_from_str};
|
||||
struct Solution {}
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::cell::RefCell;
|
||||
impl Solution {
|
||||
pub fn max_path_sum(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
|
||||
let (_,ans) = Self::dfs(&root);
|
||||
ans
|
||||
pub fn right_side_view(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
|
||||
let mut result = vec![];
|
||||
Self::dfs(root, &mut result,0);
|
||||
result
|
||||
}
|
||||
fn dfs(root: &Option<Rc<RefCell<TreeNode>>>) -> (i32, i32) {
|
||||
fn dfs(root: Option<Rc<RefCell<TreeNode>>>, mut arr: &mut Vec<i32>,depth: usize) {
|
||||
if root.is_none() {
|
||||
return (-100000000, -100000000);
|
||||
return;
|
||||
}
|
||||
let (la, ln) = Self::dfs(&root.as_ref().unwrap().borrow().left);
|
||||
let (ra, rn) = Self::dfs(&root.as_ref().unwrap().borrow().right);
|
||||
let val = root.as_ref().unwrap().borrow().val;
|
||||
let a = val.max(val + la).max(val + ra);
|
||||
let n = a.max(ln).max(rn).max(val + la + ra);
|
||||
(a, n)
|
||||
while arr.len() <= depth {
|
||||
arr.push(0);
|
||||
}
|
||||
(*arr)[depth] = root.as_ref().unwrap().borrow().val;
|
||||
Self::dfs(root.as_ref().unwrap().borrow().left.clone(), &mut arr,depth + 1);
|
||||
Self::dfs(root.as_ref().unwrap().borrow().right.clone(), &mut arr,depth + 1);
|
||||
}
|
||||
}
|
||||
fn main() {
|
||||
println!(
|
||||
"{:?}",
|
||||
Solution::max_path_sum(build_tree_from_str("[5,4,8,11,null,13,4,7,2,null,null,null,1]"))
|
||||
Solution::right_side_view(build_tree_from_str("[1,2,3,4,null,null,null,5]"))
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user