94. Binary Tree Inorder Traversal
Description of Problem
Given the root of a binary tree, return the inorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,3,2]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Constraints:
- The number of nodes in the tree is in the range
[0, 100]. 100 <= Node.val <= 100
Follow up: Recursive solution is trivial, could you do it iteratively?
Solution (Failed to answer the follow-up)
Tags: Binary Tree Rust
Code (Rust) - Recursion
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::borrow::BorrowMut;
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn inorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut v : Vec<i32> = Vec::new();
Solution::helper(root, &mut v);
return v;
}
fn helper(node: Option<Rc<RefCell<TreeNode>>>, v : &mut Vec<i32>){
if let Some(node) = node{
let node = node.borrow();
Solution::helper(node.left.clone(), v);
v.push(node.val);
Solution::helper(node.right.clone(), v);
}
}
}
Complexity
- n is the number of elements in the tree
- h is the height of the tree
Time Complexity
- \( T(n) = O(n) \)
- Traverse all nodes in tree
Auxiliary Space
- \( S(h) = O(h) \)