C++ 0ms iterative solution with Stack- BFS


  • -2
    L
    vector<int> preorderTraversal(TreeNode* root) {
    	vector<int> res; 
    	if(!root) return res;
    	
        stack<TreeNode*> BFS;
    	BFS.push(root);
    
    	while(!BFS.empty()){
    		int k=BFS.size();
    		for(int i=0;i<k;i++){
    			TreeNode* temp = BFS.top();
    
    			res.push_back(temp->val);
    			BFS.pop();
    
    			if(temp->right) BFS.push(temp->right);
    			if(temp->left) BFS.push(temp->left);
    		}
    	}
    	return res;
    }

Log in to reply
 

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