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.
Tree: Preorder Traversal
Tree: Preorder Traversal
+ 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; } } }
+ 1 comment void preOrder(Node root) { if(root==null){ return ; } System.out.print(root.data+" "); preOrder(root.left); preOrder(root.right); }
+ 5 comments Why are only C++ and Java allowed? How can others earn points?
+ 2 comments why javascript is not available to solve this beautiful prob ?
+ 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); } } }
Load more conversations
Sort 373 Discussions, By:
Please Login in order to post a comment