C++ Program on Inorder Traversal


Problem Description
Given a binary tree, return the inorder 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 inorder 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::inorderTraversal(TreeNode* root) {
    stack<TreeNode*> stack;
    vector<int>myvec;
    
	TreeNode *curr=root; 
	while(!stack.empty() || curr!=NULL)
	{
		/*If current node is not NULL push the node in stack*/
		if(curr!=NULL)              
		{
			stack.push(curr);
			curr=curr->left;
		}
		/*If current node is empty or NULL pop it from the stack */
		else                        
		{
			curr=stack.top();
			stack.pop();
			myvec.push_back(curr->val);
			curr=curr->right;
		}
	}

return myvec;

}



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.