GeeksforGeeks » Interview Questions

Microsoft Interview Question for Software Engineer/Developer (Fresher) about Trees

(3 posts)

Tags:

  1. Dedicated Programmer
    Member
    Posted 4 months ago #

    write postorder non recursive traversal algorithm.

  2. kartik
    Moderator
    Posted 4 months ago #

    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;
                    }
            }
    }
    

    Source: http://en.wikipedia.org/wiki/Tree_traversal

  3. sundi133
    guest
    Posted 4 months ago #

    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.

RSS feed for this topic