C++ with DFS solution 6ms

  • 0

    I use DFS to get the rightMost number in a row then get all the rightMost elements by looping through the height of the tree.


    vector<int> rightSideView(TreeNode* root) {
        if (!root) return vector<int>();
        int height = maxHeight(root);
        vector<int> result;
        for (int i=0; i < height; i++){
            int right = -1;
            rightMost(root, i, right);
        return result;
    void rightMost(TreeNode* root, int height, int& result){
        if (!root) return;
        if (height == 0) { 
            result = root->val;
        rightMost(root->left, height-1, result);
        rightMost(root->right, height-1, result);
    int maxHeight(TreeNode* root) {
        if (!root) return 0;
        return 1 + max(maxHeight(root->left), maxHeight(root->right));


Log in to reply

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