Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void iterativePreorder()
- {
- iterativePreorder(root);
- }
- // An iterative process to print preorder traversal of Binary tree
- void iterativePreorder(Node node) {
- // Base Case
- if (node == null) {
- return;
- }
- // Create an empty stack and push root to it
- Stack<Node> nodeStack = new Stack<Node>();
- nodeStack.push(root);
- /* Pop all items one by one. Do following for every popped item
- a) print it
- b) push its right child
- c) push its left child
- Note that right child is pushed first so that left is processed first */
- while (nodeStack.empty() == false) {
- // Pop the top item from stack and print it
- Node mynode = nodeStack.peek();
- System.out.println(mynode.info);
- nodeStack.pop();
- // Push right and left children of the popped node to stack
- if (mynode.right != null) {
- nodeStack.push(mynode.right);
- }
- if (mynode.left != null) {
- nodeStack.push(mynode.left);
- }
- }
- }
- void itPost()
- {
- if (root==null) return;
- Stack<Node> s1= new Stack<>();
- Stack<Node> s2= new Stack<>();
- s1.push(root);
- while(!s1.isEmpty())
- {
- Node temp=s1.pop();
- s2.push(temp);
- if (temp.left != null) {
- s1.push(temp.left);
- }
- if (temp.right != null) {
- s1.push(temp.right);
- }
- }
- while(!s2.isEmpty())
- {
- Node temp=s2.pop();
- System.out.println(temp.info);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement