Tree: Preorder Traversal

Sort by

recency

|

73 Discussions

|

  • + 0 comments

    golang solution Tree construction O(n log n) Tree Trasversal Print O(n)

    package main
    
    import (
    	"bufio"
    	"fmt"
    	"io"
    	"os"
    	"strconv"
    	"strings"
    )
    
    type Node struct {
    	Value int
    	Left  *Node
    	Right *Node
    }
    
    func printTree(node *Node) {
    
    	fmt.Printf("%d ", node.Value)
    
    	if node.Left != nil {
    		printTree(node.Left)
    	}
    
    	if node.Right != nil {
    		printTree(node.Right)
    	}	
    }
    
    func insertNode(node *Node, value int) {
    	if node.Value > value {
    		if node.Left == nil {
    			node.Left = &Node{
    				Value: value,
    			}
    			return
    		}
    
    		insertNode(node.Left, value)
    	} else {
    		if node.Right == nil {
    			node.Right = &Node{
    				Value: value,
    			}
    			return
    		}
    
    		insertNode(node.Right, value)
    	}
    }
    
    func contructTree(nodes []int) *Node {
    
    	// 1 <=  nodes in the tree 
    	root := &Node{
    		Value: nodes[0],
    	}
    
    	for i := 1; i < len(nodes); i++ {
    		insertNode(root, nodes[i])
    	}
    
    	return root
    }
    
    func main() {
    	reader := bufio.NewReaderSize(os.Stdin, 16*1024*1024)
    
    	readLine(reader)
    	input := strings.TrimSpace(readLine(reader))
    	stringNodes := strings.Split(input, " ")
    
    	nodes := make([]int, len(stringNodes))
    	for i, node := range stringNodes {
    		nodes[i], _ = strconv.Atoi(node)
    	}
    
    	root := contructTree(nodes)
    	printTree(root)
    }
    
    func readLine(reader *bufio.Reader) string {
    	str, _, err := reader.ReadLine()
    	if err == io.EOF {
    		return ""
    	}
    
    	return strings.TrimRight(string(str), "\r\n")
    }
    
    func checkError(err error) {
    	if err != nil {
    		panic(err)
    	}
    }
    
  • + 0 comments

    The tricky part is how to convert input to the tree, other than the traversal...

  • + 0 comments

    This is one possible solution in python

    def preOrder(root):
        if root:
            print(root, end=' ')
            preOrder(root.left)
            preOrder(root.right)
    
  • + 0 comments

    C++ O(n)

    an elegant way to write it is by using recursion:

    void preOrder(Node *root) {
        if(root == NULL) return;
    
        std::cout << root->data << " ";
    
        preOrder(root->left);
        preOrder(root->right);
    }
    
  • + 0 comments

    This is a terribly written problem.