C++ Solution, Using preorder to solve levelorder.


  • 0
    C

    use a number(level) as index to mark the level of every node.
    '''
    class Solution {
    public:
    vector<vector<int>> res;
    int level = 0;
    vector<vector<int>> levelOrder(TreeNode* root) {
    Traversal(root);
    return res;
    }
    void Traversal(TreeNode* root){
    if (root == NULL){
    level++;
    return;
    }

    	if (res.size()<=level){
    		vector<int> newv;
    		res.push_back(newv);
    		res[level++].push_back(root->val);
    	}
    	else{
    		res[level++].push_back(root->val);
    	}
    	
    	Traversal(root->left);
    	level--;
    	Traversal(root->right);
    	level--;
    }
    

    };
    '''


Log in to reply
 

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