199. Binary Tree Right Side View

Problem:

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

Solutions:

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

    void helper(TreeNode* root, int level, vector<int>& ret) {
        if (root == nullptr)    return;
        if (ret.size() == level)    ret.push_back(root->val);
        helper(root->right, level + 1, ret);
        helper(root->left, level + 1, ret);
    }
};

results matching ""

    No results matching ""