leetcode 199. Binary Tree Right Side View 树的先序遍历

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 <—

很巧妙的先序遍历

/**
 * 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> res;
        dfs(root, res, 0);
        return res;
    }
    void dfs(TreeNode* r, vector<int>& res, int d){
        if(r==NULL)return;
        if(res.size()==d)
            res.push_back(r->val);
        dfs(r->right, res, d+1);
        dfs(r->left, res, d+1);
    }
};
posted @ 2020-07-25 17:24  winechord  阅读(60)  评论(0编辑  收藏  举报