My solution - no special cases, single traversal, tracking depth


  • 1
    F

    Solutions submitted seemed overengineered. This can be answered using a simple depth first postorder traversal, tracking the max depth seen so far. 8ms runtime:

    class Solution {
    public:
        vector<int> rightSideView(TreeNode *root) {
            traverse(root, 0);
            return result;
        }
        
        void traverse(TreeNode *node, int currentDepth) {
            if (!node)
                return; 
                
            if (currentDepth > seenDepth) {
                result.push_back(node->val);
                seenDepth = currentDepth;
            }
            
            traverse(node->right, currentDepth+1);
            traverse(node->left, currentDepth+1);
        }
        
        vector<int> result;
        int seenDepth = -1;
    };

  • 0
    F

    very neat and elegant!


Log in to reply
 

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