Preorder、inorder、postorder iterative solution by c++


  • 17
    H

    preorder:

    vector<int> preorderTraversal(TreeNode* root) {
    	vector<int> res;
    	std::stack<TreeNode*> temp;
    	while (root || !temp.empty()) {
    		while (root) {
    			temp.push(root);
    			res.push_back(root->val);
    			root = root->left;
    		}
    		root = temp.top();
    		temp.pop();
    		root = root->right;
    	}
    	return res;
    }
    

    inorder:

    vector<int> inorderTraversal(TreeNode* root) {
    	vector<int> res;
    	std::stack<TreeNode*> temp;
    	while (root || !temp.empty()) {
    		while (root) {
    			temp.push(root);
    			root = root->left;
    		}
    		root = temp.top();
    		temp.pop();
    		res.push_back(root->val);
    		root = root->right;
    	}
    	return res;
    }
    

    postorder:

    vector<int> postorderTraversal(TreeNode* root) {
    	vector<int> res;
    	std::stack<TreeNode*> temp;
    	while (root || !temp.empty()) {
    		while (root) {
    			temp.push(root);
    			res.insert(res.begin(),root->val);
    			root = root->right;
    		}
    		root = temp.top();
    		temp.pop();
    		root = root->left;
    	}
    	return res;
    }

  • 0
    S

    why cant we do root=temp.pop(); ??


  • 0
    Z

    @sauravk it's c++, not java,you cannot do it in one step


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.