|
|
|
@ -4,7 +4,7 @@
|
|
|
|
|
* Author: xBLACKICEx (xBLACKICE@outlook.com)
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
use hello_algo_rust::include::{print_util, vec_to_tree, TreeNode};
|
|
|
|
|
use hello_algo_rust::include::{vec_to_tree, TreeNode, print_util};
|
|
|
|
|
use hello_algo_rust::op_vec;
|
|
|
|
|
|
|
|
|
|
use std::cell::RefCell;
|
|
|
|
@ -14,17 +14,12 @@ use std::rc::Rc;
|
|
|
|
|
fn pre_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
|
|
|
|
|
let mut result = vec![];
|
|
|
|
|
|
|
|
|
|
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
|
|
|
|
|
if let Some(node) = root {
|
|
|
|
|
// 访问优先级:根节点 -> 左子树 -> 右子树
|
|
|
|
|
let node = node.borrow();
|
|
|
|
|
res.push(node.val);
|
|
|
|
|
dfs(node.left.as_ref(), res);
|
|
|
|
|
dfs(node.right.as_ref(), res);
|
|
|
|
|
}
|
|
|
|
|
if let Some(node) = root {
|
|
|
|
|
// 访问优先级:根节点 -> 左子树 -> 右子树
|
|
|
|
|
result.push(node.borrow().val);
|
|
|
|
|
result.extend(pre_order(node.borrow().left.as_ref()));
|
|
|
|
|
result.extend(pre_order(node.borrow().right.as_ref()));
|
|
|
|
|
}
|
|
|
|
|
dfs(root, &mut result);
|
|
|
|
|
|
|
|
|
|
result
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
@ -32,17 +27,12 @@ fn pre_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
|
|
|
|
|
fn in_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
|
|
|
|
|
let mut result = vec![];
|
|
|
|
|
|
|
|
|
|
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
|
|
|
|
|
if let Some(node) = root {
|
|
|
|
|
// 访问优先级:左子树 -> 根节点 -> 右子树
|
|
|
|
|
let node = node.borrow();
|
|
|
|
|
dfs(node.left.as_ref(), res);
|
|
|
|
|
res.push(node.val);
|
|
|
|
|
dfs(node.right.as_ref(), res);
|
|
|
|
|
}
|
|
|
|
|
if let Some(node) = root {
|
|
|
|
|
// 访问优先级:左子树 -> 根节点 -> 右子树
|
|
|
|
|
result.extend(in_order(node.borrow().left.as_ref()));
|
|
|
|
|
result.push(node.borrow().val);
|
|
|
|
|
result.extend(in_order(node.borrow().right.as_ref()));
|
|
|
|
|
}
|
|
|
|
|
dfs(root, &mut result);
|
|
|
|
|
|
|
|
|
|
result
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
@ -50,18 +40,12 @@ fn in_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
|
|
|
|
|
fn post_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
|
|
|
|
|
let mut result = vec![];
|
|
|
|
|
|
|
|
|
|
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
|
|
|
|
|
if let Some(node) = root {
|
|
|
|
|
// 访问优先级:左子树 -> 右子树 -> 根节点
|
|
|
|
|
let node = node.borrow();
|
|
|
|
|
dfs(node.left.as_ref(), res);
|
|
|
|
|
dfs(node.right.as_ref(), res);
|
|
|
|
|
res.push(node.val);
|
|
|
|
|
}
|
|
|
|
|
if let Some(node) = root {
|
|
|
|
|
// 访问优先级:左子树 -> 右子树 -> 根节点
|
|
|
|
|
result.extend(post_order(node.borrow().left.as_ref()));
|
|
|
|
|
result.extend(post_order(node.borrow().right.as_ref()));
|
|
|
|
|
result.push(node.borrow().val);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
dfs(root, &mut result);
|
|
|
|
|
|
|
|
|
|
result
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|