给定一个二叉树的根节点root,返回它的中序遍历结果。
数据范围:树上节点数满足
,树上每个节点的值满足 
进阶:空间复杂度
,时间复杂度 )
进阶:空间复杂度
{1,2,#,#,3}[2,3,1]
{}[]
{1,2}[2,1]
{1,#,2}[1,2]
树中节点数目在范围 [0, 100] 内树中的节点的值在[-100,100]以内
/**
* #[derive(PartialEq, Eq, Debug, Clone)]
* pub struct TreeNode {
* pub val: i32,
* pub left: Option<Box<TreeNode>>,
* pub right: Option<Box<TreeNode>>,
* }
*
* impl TreeNode {
* #[inline]
* fn new(val: i32) -> Self {
* TreeNode {
* val: val,
* left: None,
* right: None,
* }
* }
* }
*/
struct Solution{
}
impl Solution {
fn new() -> Self {
Solution{}
}
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型一维数组
*/
pub fn inorderTraversal(&self, root: Option<Box<TreeNode>>) -> Vec<i32> {
// write code here
let mut v = Vec::new();
self.f(root, &mut v);
v
}
fn f(&self,mut node: Option<Box<TreeNode>>, v: &mut Vec<i32>) {
if node.is_none() {return}
self.f(node.as_mut().unwrap().left.take(), v);
v.push(node.as_mut().unwrap().val);
self.f(node.as_mut().unwrap().right.take(), v);
}
}
struct Solution{
}
impl Solution {
fn new() -> Self {
Solution{}
}
pub fn inorderTraversal(&self, root: Option<Box<TreeNode>>) -> Vec<i32> {
// write code here
let mut res = vec![];
fn dfs(node: &Option<Box<TreeNode>>, arr: &mut Vec<i32>) {
if let Some(ref node) = *node {
dfs(&node.left, arr);
arr.push(node.val);
dfs(&node.right, arr);
}
}
dfs(&root, &mut res);
res
}
}