GeeksforGeeks » Interview Questions
Microsoft Interview Question for Software Engineer/Developer (Fresher) about Trees
(3 posts)-
write postorder non recursive traversal algorithm.
-
void iterativePostOrder(Node* root) { if (!root) { return; } stack<Node*> nodeStack; Node* cur = root; while (true) { if (cur) { if (cur->right) { nodeStack.push(cur->right); } nodeStack.push(cur); cur = cur->left; continue; } if (nodeStack.empty()) { return; } cur = nodeStack.top(); nodeStack.pop(); if (cur->right && !nodeStack.empty() && cur->right == nodeStack.top()) { nodeStack.pop(); nodeStack.push(cur); cur = cur->right; } else { std::cout << cur->val << " "; cur = NULL; } } } -
private void printPreOrderStack(Node root1) { if(root1==null) return; StackX a = new StackX(); a.pushnod(root1); while(!a.isEmpty()){ Node node = a.popNod(); if(node==null){ continue; }else{ System.out.print(" " + node.value); } a.pushnod(node.right); a.pushnod(node.left); } }
Reply
You must log in to post.