Tree: Preorder Traversal

Sort by

recency

|

444 Discussions

|

  • + 0 comments

    JavaScript solution using recursion

    function preOrder(root) {
        let res = '';
        function abc(root){
          if(root){
            res = res + root.data + '  ';
            abc(root.left);
            abc(root.right)  
           }
        }
        abc(root);
        console.log(res)
    }
    
  • + 0 comments

    Haskell

    It would have been nice if the problem statement gave an actual sample of the expected input data and how to parse it... Bad form, folks.

    module Main where
    
    data Tree = Empty | Node Int Tree Tree
    
    instance Show Tree where
        show Empty = ""
        show (Node x l r) =
            show x ++ " " ++ show l ++ show r
    
    insert :: Tree -> Int -> Tree
    insert Empty x = Node x Empty Empty
    insert (Node k left right) x
        | x < k = Node k (insert left x) right
        | otherwise = Node k left (insert right x)
    
    parseTree :: [Int] -> Tree
    parseTree = foldl insert Empty
    
    main :: IO ()
    main = do
        _ <- getLine
        seq <- map read . words <$> getLine :: IO [Int]
        print $ parseTree seq
    
  • + 0 comments

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

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

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

    n=int(input()) nums=list(map(int,input().split())) tree=Tree() tree.root=Node(nums[0]) for num in nums[1:]: tree.insert(tree.root,num) tree.preOrder(tree.root)

  • + 0 comments

    There is a gotcha here, that the C# template doesn't parse the input like the languages. And the description doesn't describe how to parse the input.

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