Tree: Inorder Traversal

Sort by

recency

|

206 Discussions

|

  • + 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);
            }
        }
    
  • + 0 comments
    def inOrder(root):
        result = []
        
        def traverse(node):
            if not node:
                return
            traverse(node.left)
            result.append(str(node.info))
            traverse(node.right)
    
        traverse(root)
        print(" ".join(result))
    
  • + 0 comments

    JavaScript:

    function inOrder(root) {
      let answer = '';
      
      function process(node) {
        if(node!=null) {
          process(node.left);
          answer += `${node.data} `;
          process(node.right);
        }
      }
      process(root);
      
      console.log(answer);
      
    }