Different results on my machine and yours


  • 0
    Q

    Following is my code:

    class Solution {
    public:
        vector<int> preorderTraversal(TreeNode *root) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            vector<int> res;
    		stack<TreeNode *> s;
    		TreeNode * work = NULL;
    		if(root == NULL)return res;
    		s.push(root);
    		while(!s.empty()){
    			work = s.top();
    			s.pop();
    			res.push_back(work->val);
    			if(work->left == NULL && work->right){
    				s.push(work->right);
    				continue;
    			}
    			while(work->left){
    				work = work->left;
    				res.push_back(work->val);
    				if(work->right)s.push(work->right);
    			}
    		}
    		return res;
        }
    };
    

    I got wrong answer to the input [3,1,2], the expected output is [3,1,2] while my program output [3,1].
    However, on my own machine(visual studio 2010), the program indeed output [3,1,2]. I have no idea how this happened. Could any one help me?


  • 4
    P

    The following code doesn't make sense.

            if(work->left == NULL && work->right){
                s.push(work->right);
                continue;
            }
    

    try

            if(work->right) {
                s.push(work->right);
            }
    

    Or

    class Solution {
    public:
        vector<int> preorderTraversal(TreeNode *root) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            vector<int> res;
            stack<TreeNode *> s;
            TreeNode * work = NULL;
            if(root == NULL)return res;
            s.push(root);
            while(!s.empty()){
                work = s.top();
                s.pop();
                while(work){
                    res.push_back(work->val);
                    if(work->right)s.push(work->right);
                    work = work->left;
                }
            }
            return res;
        }
    };

  • 0
    Q

    Thanks very much, that solved my problem!!


  • 0
    P

    Please select my answer =)


  • 0
    A
    This post is deleted!

  • 0
    S
    This post is deleted!

  • 0
    Y

    Thanks for your answer! But why did the previous code get different results on different machines?


Log in to reply
 

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