897. Increasing Order Search Tree
Given the root
of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.
Example 1:

Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9] Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
Example 2:

Input: root = [5,1,7] Output: [1,null,5,null,7]
Constraints:
- The number of nodes in the given tree will be in the range
[1, 100]
. 0 <= Node.val <= 1000
Rust Solution
struct Solution;
use rustgym_util::*;
trait Inorder {
fn inorder(self, next: TreeLink) -> TreeLink;
}
impl Inorder for TreeLink {
fn inorder(self, next: TreeLink) -> TreeLink {
if let Some(node) = self.as_ref() {
let mut node = node.borrow_mut();
let left = node.left.take();
let right = node.right.take();
let res = Self::inorder(left, self.clone());
node.right = Self::inorder(right, next);
res
} else {
next
}
}
}
impl Solution {
fn increasing_bst(root: TreeLink) -> TreeLink {
root.inorder(None)
}
}
#[test]
fn test() {
let root = tree!(
5,
tree!(3, tree!(2, tree!(1), None), tree!(4)),
tree!(6, None, tree!(8, tree!(7), tree!(9)))
);
let res = tree!(
1,
None,
tree!(
2,
None,
tree!(
3,
None,
tree!(
4,
None,
tree!(
5,
None,
tree!(6, None, tree!(7, None, tree!(8, None, tree!(9))))
)
)
)
)
);
assert_eq!(Solution::increasing_bst(root), res);
}
Having problems with this solution? Click here to submit an issue on github.