C++ Program on Postorder Traversal


Problem Description
Given a binary tree, return the Postorder traversal of its nodes values..

Problem Constraints
1 <= number of nodes <= 105

Input Format
First and only argument is root node of the binary tree, A..

Output Format
Return an integer array denoting the Postorder traversal of the given binary tree..

/**
 /**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
vector<int> Solution::postorderTraversal(TreeNode* A) {

    stack<TreeNode*> post;
	post.push(A);
    vector<int>vec;
	
	stack<int> pout;
	while(!post.empty())
	{
		TreeNode *curr=post.top();
		post.pop();
		pout.push(curr->val);
		
		if(curr->left)
		{
			post.push(curr->left);
		}
		if(curr->right)
		{
			post.push(curr->right);
		}
	}

	while(!pout.empty())
	{
		vec.push_back(pout.top());
		pout.pop();
	}

    return vec;

}



MCQs

About Us | Contact Us | Privacy Policy | Career  | Online Training
Youtube   LinkedIn   Facebook   Twitter   Instagram  
Copyright©CppBuzz.com
Like many websites, we use cookies to ensure best browsing experience on our website. While using this website, you acknowledge to have read and accepted our cookie and privacy policy.