Macro leetcode_trees_rs::utils::symmetric_tree
source · macro_rules! symmetric_tree { ($val:expr) => { ... }; ($val:expr, $($both_sides:tt)*) => { ... }; }
Expand description
A re-export for the symmetric_tree!, right_tree! and left_tree! macros.
All of the TreeNode macros can be used to also just generate a new TreeNode
instance without
expanding on it.
§Description
A macro to reduce the boilerplate in generating symmetric binary trees.
§Match arms
Arm 1:
- Takes the value as an argument.
- Equivalent of doing
TreeNode::new()
. Arm 2: - Takes the value as an argument.
- Also takes a sequence of left and right node values at the same time (which means they’re
symmetric) as an argument (and builds the
TreeNode
struct with them).
§Example usage
use crate::utils::symmetric_tree;
symmetric_tree!(1, 2, 3, 4)
The symmetric_tree! macro invocation is desugared to this:
use std::rc::Rc;
use std::cell::RefCell;
use crate::utils::TreeNode;
TreeNode {
val: 1,
left: Some(Box::new(TreeNode {
val: 2,
left: Some(Box::new(TreeNode {
val: 3,
left: Some(Box::new(TreeNode {
val: 4,
left: None,
right: None,
}))
right: Some(Box::new(TreeNode {
val: 4,
left: None,
right: None,
}))
}))
right: Some(Box::new(TreeNode {
val: 3,
left: Some(Box::new(TreeNode {
val: 4,
left: None,
right: None,
}))
right: Some(Box::new(TreeNode {
val: 4,
left: None,
right: None,
}))
}))
}))
right: Some(Box::new(TreeNode {
val: 2,
left: Some(Box::new(TreeNode {
val: 3,
left: Some(Box::new(TreeNode {
val: 4,
left: None,
right: None,
}))
right: Some(Box::new(TreeNode {
val: 4,
left: None,
right: None,
}))
}))
right: Some(Box::new(TreeNode {
val: 3,
left: Some(Box::new(TreeNode {
val: 4,
left: None,
right: None,
}))
right: Some(Box::new(TreeNode {
val: 4,
left: None,
right: None,
}))
}))
}))
}
I bet you don’t want to write that every time. You can have greater control with this too:
use crate::utils::{symmetric_tree, TreeNode};
TreeNode {
val: 1,
left: None,
right: Some(Box::new(symmetric_tree!(2, 3, 4)))
}
Now you have a tree that branches all the way through the right side without having anything on the left.