Tree: Inorder Traversal

Sort by

recency

|

208 Discussions

|

  • + 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);
    }
    
  • + 0 comments

    class Node: def init(self, val): self.value = val self.right = None self.left = None

    class Tree: def init(self): self.root = None

    def insert(self, root, val):
        if root is None:
            return Node(val)
        elif val < root.value:
            if root.left is None:
                root.left = Node(val)
            else:
                self.insert(root.left, val)
        else:
            if root.right is None:
                root.right = Node(val)
            else:
                self.insert(root.right, val)
        return root
    
    def inorder(self, root):
        if root is None:
            return 
        self.inorder(root.left)
        print(root.value, end=' ')
        self.inorder(root.right)
    

    n=int(input()) numbers = list(map(int,input().split()))

    Initialize the tree and create root

    tree = Tree() tree.root = Node(numbers[0])

    Insert remaining numbers

    for number in numbers[1:]: tree.insert(tree.root, number)

    Perform in-order traversal

    tree.inorder(tree.root)

  • + 0 comments

    for C# language the input should be read from stdin, but how to construct a tree from it? Typically you construct a binary tree from array using rules: The left child of the node at index i is at index 2*i + 1. The right child of the node at index i is at index 2*i + 2

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