Here is my AC solution, is there any better one?


  • 0
    R

    use recursion method to get element at each level.

    class Solution {
        public:
            vector<vector<int> > levelOrder(TreeNode *root);
            int printNodeAtLevel(TreeNode *root, vector<int> &levelData, int level);
        };
        
        int Solution::printNodeAtLevel(TreeNode *root, vector<int> &levelData, int level){
            if (root == NULL || level < 0)
                return 0;
            if (level == 0){
                levelData.push_back(root->val);
                return 1;
            }
            return printNodeAtLevel(root->left, levelData, level - 1) + printNodeAtLevel(root->right, levelData, level - 1);
        }
        
        vector< vector<int> > Solution::levelOrder(TreeNode *root){
            vector< vector<int> > res;
            if (root == NULL)
                return res;
            for (int level = 0; ; level++){
                vector<int> levelData;
                if (printNodeAtLevel(root, levelData, level)){
                    res.push_back(levelData);
                }else{
                    break;
                }  
            }   
            return res;
        }

  • 0
    F
    This post is deleted!

  • 0
    S

    Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the Discuss FAQ for more info. Take a look at good sharing example


Log in to reply
 

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