Easy C++ Solution. Only add four lines to Binary Tree Level Order Traversal.


  • 0
    C

    Easy C++ Solution. Only add four lines to Binary Tree Level Order Traversal.
    When the level%2 is 1, use insert instead of push_back.

    class Solution {
    public:
    	vector<vector<int>> res;
    	int level = 0;
    	vector<vector<int>> zigzagLevelOrder(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{
    			if (level % 2 == 1){
    				res[level].insert(res[level].begin(), root->val);
    				level++;
    			}
    			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.