Can anybody help me to transform my cpp into java


  • 0
    A
    class Solution {
    public:
        vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
            vector<vector<int>> result;
            //if(!root) return result;
            travers(result,root,0,true);
            return result;
        }
    private:
        void travers(vector<vector<int>>& result,TreeNode* root,int level,bool left_to_right)
        {
            if(!root) return;
            if(level+1>result.size()) result.push_back(vector<int>());
            if(left_to_right)
            {
                result[level].push_back(root->val);
            }
            else
            {
                result[level].insert(result[level].begin(),root->val);
            }
            travers(result,root->left,level+1,!left_to_right);
            travers(result,root->right,level+1,!left_to_right);
        }
    };
    

    this is my code for cpp, and I want to change it into java, but I am not a good java coder, so what I got is :

    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            ArrayList<ArrayList<Integer>> result;
            traverse(result,root,0,true);
            return result;
        }
        private void traverse(List<List<Integer>> result,TreeNode root,Integer level,boolean left_to_right)
        {
            if(!root) return;
            if(level+1>result.size()) //result.add(result.size()-1,ArrayList<Integer>>();
            {
                List<Integer> temp = new ArrayList<Integer>();
                result.add(result.size()-1,temp);
            }
            if(left_to_right) result[level].add(result[level].size()-1,root.val);
            else result[level].add(0,root.val);
            traverse(result,root.left,level+1,!left_to_right);
            traverse(result,root.right,level+1,!left_to_right);
    }
    

    can anybody tell me what should I do to make it right? Thank you very much....


Log in to reply
 

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