Java Program to Perform the inorder tree traversal


Perform the inorder tree traversal

Rust Programming Language


Perform the inorder tree traversal


Problem


Rust program that performs an inorder traversal of a binary tree.

Input


struct TreeNode {
    val: i32,
    left: Option<Box<TreeNode>>,
    right: Option<Box<TreeNode>>,
}

impl TreeNode {
    fn new(val: i32) -> Self {
        Self { val, left: None, right: None }
    }
}

fn inorder_traversal(root: Option<Box<TreeNode>>) {
    if let Some(node) = root {
        inorder_traversal(node.left);
        println!("{}", node.val);
        inorder_traversal(node.right);
    }
}

fn main() {
    // Construct the tree
    let mut root = TreeNode::new(1);
    root.left = Some(Box::new(TreeNode::new(2)));
    root.right = Some(Box::new(TreeNode::new(3)));
    root.left.as_mut().unwrap().left = Some(Box::new(TreeNode::new(4)));
    root.left.as_mut().unwrap().right = Some(Box::new(TreeNode::new(5)));
    root.right.as_mut().unwrap().left = Some(Box::new(TreeNode::new(6)));
    root.right.as_mut().unwrap().right = Some(Box::new(TreeNode::new(7)));

    // Perform the inorder traversal
    println!("Inorder traversal:");
    inorder_traversal(Some(Box::new(root)));
}{codeBox}

Output


Inorder traversal:
4
2
5
1
6
3
7{codeBox}

Explanation


In this implementation, the TreeNode struct represents a node in the binary tree. Each node has a value and pointers to its left and right children. The inorder_traversal function performs an inorder traversal of the tree recursively by first visiting the left subtree, then printing the current node's value, and finally visiting the right subtree. The main function constructs a sample tree and performs an inorder traversal of the tree, printing out the values of each visited node.


Post a Comment