Skip to content

Latest commit

 

History

History
99 lines (84 loc) · 2.47 KB

_199. Binary Tree Right Side View.md

File metadata and controls

99 lines (84 loc) · 2.47 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : July 04, 2024

Last updated : July 04, 2024


Related Topics : Tree, Depth-First Search, Breadth-First Search, Binary Tree

Acceptance Rate : 65.78 %


Solutions

C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> output;
        rsvHelper(root, 0, &output);
        return output;
    }

    void rsvHelper(TreeNode* curr, int depth, vector<int>* output) {
        if (not curr)
            return;
        if (depth == output->size())
            output->push_back(curr->val);
        
        depth++;
        rsvHelper(curr->right, depth, output);
        rsvHelper(curr->left, depth, output);
    }
};

Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> output = new LinkedList<>();
        rsvHelper(root, 0, output);
        return output;
    }

    private void rsvHelper(TreeNode curr, int depth, List<Integer> output) {
        if (curr == null) {
            return;
        }
        if (depth == output.size()) {
            output.add(curr.val);
        }

        depth++;
        rsvHelper(curr.right, depth, output);
        rsvHelper(curr.left, depth, output);
    }
}