We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Hackerrank Home
  • Prepare
    NEW
  • Certify
  • Compete
  • Career Fair
  • Hiring developers?
  1. Prepare
  2. Data Structures
  3. Trees
  4. Tree: Preorder Traversal
  5. Discussions

Tree: Preorder Traversal

Problem
Submissions
Leaderboard
Discussions
Editorial

Sort 373 Discussions, By:

votes

Please Login in order to post a comment

  • im_priyank_jain
    5 years ago+ 12 comments

    Morris Traversal without using Recursion & Stack

    Node pre;
        if(root == null)
            return;
        Node curr = root;
        while(curr != null){
            if(curr.left == null){
                System.out.print(curr.data+" ");
                curr = curr.right;
            }else{
                 pre = curr.left;
                 while(pre.right !=null && pre.right != curr)
                     pre = pre.right;
                 if(pre.right == null){
                     pre.right = curr;
                     System.out.print(curr.data+" ");
                     curr = curr.left;
                 }else{
                     pre.right=null;
                     curr=curr.right;
                 }
            }
        }
    
    37|
    Permalink
    View more Comments..
  • shanker4999
    6 years ago+ 1 comment
    void preOrder(Node root) {
        if(root==null){
            return ;
        }
        System.out.print(root.data+" ");
        preOrder(root.left);
        preOrder(root.right);
    }
    
    24|
    Permalink
  • Matt_Scandale
    7 years ago+ 5 comments

    Why are only C++ and Java allowed? How can others earn points?

    9|
    Permalink
    View more Comments..
  • Range
    5 years ago+ 2 comments

    why javascript is not available to solve this beautiful prob ?

    6|
    Permalink
  • pmtatar
    2 years ago+ 0 comments

    java8

    Recursive Solution

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

    Non recursive solution

    public static void preOrder(Node root) {
        Stack<Node> stack = new Stack<>();
        stack.push(root);
        while (!stack.empty()) {
            Node node = stack.pop();
            if (node != null) {
                System.out.print(node.data + " ");
                stack.push(node.right);
                stack.push(node.left);
            }
        }
    }
    
    5|
    Permalink
Load more conversations

Need Help?


View editorial
View top submissions
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature