Is the test case of this problem very small?


  • 0
    K

    I get accepted by using the following buggy solution, but the same solution can't pass the Problem Binary Tree Level Order Traversal II.

    class Solution {
    public:
        vector<vector<int> > levelOrder(TreeNode *root) {
            //@ret: answer we will return 
            vector<vector<int> > ret;
            //travel the tree and calculate the answer
            process(root, 1, ret);
            //return the answer
            return ret;
        }
        //return the level of x
        //@x: the index of the node (>=1)
        int log2(int x)
            {
                int ret = 0;
                while((1<<ret) <= x)
                    ++ret;
                return ret-1;
            }
        //travel the tree
        void process(TreeNode *cur, int key, vector<vector<int> > &ret)
            {
    	    //the tree is empty
                if(NULL == cur)
                    return;
    	    //get the index of current node
    	    int idx = log2(key);
    	    //push a new level into the ret if needed
    	    if(idx>=ret.size())
    		ret.push_back(vector<int>());
    	    ret[idx].push_back(cur->val);
    	    //process the left subtree
    	    //!!!!!!!!!!!be careful!!!!!!!
    	    //key*2 will be very large!!!!!!!!!
    	    //!!!!!may not in the range of int!!!!!!!!!!!!!!
                process(cur->left, key*2, ret);
    	    //process the right subtree
                process(cur->right, key*2+1, ret);
            }
    };

  • 0
    L

    What is the question? If this is about "Binary Tree Level Order Traversal II", please post a question there and explain in plain text how you solve "Binary Tree Level Order Traversal", how you're trying to solve "Binary Tree Level Order Traversal II", why you think it doesn't work, etc.


Log in to reply
 

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