diff --git "a/problems/0337.\346\211\223\345\256\266\345\212\253\350\210\215III.md" "b/problems/0337.\346\211\223\345\256\266\345\212\253\350\210\215III.md" index ca8cea2369..1708b7a1e8 100644 --- "a/problems/0337.\346\211\223\345\256\266\345\212\253\350\210\215III.md" +++ "b/problems/0337.\346\211\223\345\256\266\345\212\253\350\210\215III.md" @@ -490,6 +490,33 @@ function robNode(node: TreeNode | null): MaxValueArr { } ``` +### Rust + +动态规划: + +```rust +use std::cell::RefCell; +use std::rc::Rc; +impl Solution { + pub fn rob(root: Option>>) -> i32 { + let (v1, v2) = Self::rob_tree(&root); + v1.max(v2) + } + pub fn rob_tree(cur: &Option>>) -> (i32, i32) { + match cur { + None => (0, 0), + Some(node) => { + let left = Self::rob_tree(&node.borrow_mut().left); + let right = Self::rob_tree(&node.borrow_mut().right); + ( + left.0.max(left.1) + right.0.max(right.1), // 偷左右节点 + node.borrow().val + left.0 + right.0, // 偷父节点 + ) + } + } + } +} +```