Tree: Preorder Traversal

Sort by

recency

|

442 Discussions

|

  • + 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);
            }
        }
    
  • + 1 comment

    def preOrder(root): if(root==None): return 0 print(root.info, end=" ") preOrder(root.left) preOrder(root.right)

  • + 0 comments

    JAVA:

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