Tree: Inorder Traversal

Sort by

recency

|

211 Discussions

|

  • + 0 comments

    My Java solution with linear time complexity and o(h) space complexity:

    public static void inOrder(Node root) {
            if(root == null) return;
            
            inOrder(root.left);
            System.out.print(root.data + " ");
            inOrder(root.right);
        }
    
  • + 0 comments

    C

    void inOrder( struct node *root) {
        if(!root) return;
        inOrder(root->left);
        printf("%d ", root->data); 
        inOrder(root->right);
    }
    
  • + 0 comments

    Python

    def inOrder(root):
        if root is None:
            return
        inOrder(root.left)
        print(root.info,end=" ")
        inOrder(root.right)
    
  • + 0 comments

    Haskell

    module Main where
    
    data Tree a = Empty | Node a (Tree a) (Tree a) deriving (Show)
    
    inOrder :: Tree a -> [a]
    inOrder Empty = []
    inOrder (Node a left right) = inOrder left ++ [a] ++ inOrder right
    
    insertNode :: (Ord a) => Tree a -> a -> Tree a
    insertNode Empty x = Node x Empty Empty
    insertNode (Node a left right) x
        | x < a = Node a (insertNode left x) right
        | x > a = Node a left (insertNode right x)
        | otherwise = Node a left right
    
    main :: IO ()
    main =
        interact $
            unwords . map show . inOrder . foldl insertNode Empty . map (read :: String -> Int) . words . (!! 1) . lines
    
  • + 0 comments

    Performs an in-order traversal of a binary tree.

    public static void inOrder(Node root) {
        // Base Case: If the node is null, return (end recursion)
        if (root == null) {
            return;
        }
    
        // Recursive Step: Traverse the left subtree
        inOrder(root.left);
    
        // Process the current node (print its value)
        System.out.print(root.data + " ");
    
        // Recursive Step: Traverse the right subtree
        inOrder(root.right);
    }