Level Order Traversal C++ Solution


  • 0
    N

    Solution: Do level order traversal and push the rightmost node in every level to the result vector.

    vector<int> res;
    
    void levelOrderTraversal(TreeNode *root, int level, int* current_max_level) {
        if(root == NULL)  return;
        
        if(*current_max_level < level) {
            *current_max_level = level;
            res.push_back(root->val);
        }
        
        levelOrderTraversal(root->right, level+1, current_max_level);
        levelOrderTraversal(root->left, level+1, current_max_level);
    }
    
    vector<int> rightSideView(TreeNode *root) {
        int level = 1;
        int current_max_level = 0;
        levelOrderTraversal(root, level, &current_max_level);
        return res;
    }

Log in to reply
 

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