Tree: Postorder Traversal

Sort by

recency

|

228 Discussions

|

  • + 0 comments

    Haskell

    module Main where
    
    data Tree = Empty | Node Int Tree Tree
    
    instance Show Tree where
        show Empty = ""
        show (Node x l r) =
            show l ++ show r ++ show x ++ " "
    
    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
    public static void postOrder(Node root) {
            if(root != null){
                postOrder(root.left);
                postOrder(root.right);
                System.out.print(root.data+" ");
            }
        }
    
  • + 0 comments

    Javascript:

    function postOrder(root) {
    	  let result = []
    		let values = ""
        
        function dfsPostTraverse(currentNode){
            if(currentNode == null){
                return;
            }
            dfsPostTraverse(currentNode.left)
            dfsPostTraverse(currentNode.right)
            result.push(currentNode.data)
        }
        
        dfsPostTraverse(root)
        
        for(let i=0; i<result.length; i++){
            values += result[i] + " "
        }
        console.log(values)
    }
    
  • + 0 comments
    def postOrder(root):
        result = []
        
        def traverse(node):
            if not node:
                return
            traverse(node.left)
            traverse(node.right)
            result.append(str(node.info))
            
        traverse(root)
        print(" ".join(result))
    
  • + 0 comments

    solution for java

    public static void postOrder(Node root) {

        if(root==null) return;
    
        postOrder(root.left);
    
        postOrder(root.right);
        System.out.print(root.data+" ");
    }