LeetCode 0199 - Binary Tree Right Side View

2021-08-11 14:59:09 浏览数 (1)

Binary Tree Right Side View

Desicription

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:

代码语言:javascript复制
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

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

Solution

代码语言:javascript复制
/**
 * 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 {
private:
    void fun(vector<int>& res, int level, TreeNode* root) {
        if(root == NULL)
            return ;
        if(res.size() < level)
            res.push_back(root->val);
        fun(res, level 1, root->right);
        fun(res, level 1, root->left);
    }
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> res;
        fun(res, 1, root);
        return res;
    }
};

0 人点赞