Timeline
inorder traversal
Problem:
Inorder traversal, return when reaching the kth element.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| struct Solution;
#[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::rc::Rc; use std::cell::RefCell; use std::collections::VecDeque; impl Solution { pub fn kth_smallest(root: Option<Rc<RefCell<TreeNode>>>, k: i32) -> i32 { let mut stack = VecDeque::new(); let mut p = root; let mut count = 0; let mut res = 0;
while p.is_some() || !stack.is_empty(){ if let Some(node) = p{ stack.push_back(node.clone()); p = node.borrow().left.clone(); }else{ count +=1; let curr = stack.pop_back().unwrap(); if count == k{ res = curr.borrow().val; break; } p = curr.borrow().right.clone(); } } res } }
fn main() { println!("Hello, world!"); }
|
leetcode hot 100 rewrite
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| #include <stack> using std::stack;
class Solution { public: int kthSmallest(TreeNode *root, int k) { stack<TreeNode *> stk;
TreeNode *p = root; int cnt = 0;
while (p || !stk.empty()) { if (p) { stk.push(p); p = p->left; } else { p = stk.top(); stk.pop();
cnt++; if (cnt == k) break;
p = p->right; } }
return p->val; } };
|