199. Binary Tree Right Side View

相比上一题水多了,但是自己一开始也想错了

dfs,bfs都可以,保存每层最右结果就好了

/**
 * 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:
    
    int maxdep;
    vector<int> ans;
    
    void dfs(TreeNode* root, int depth) {
        if (!root)
            return;
        if (depth > maxdep) {
            ans.push_back(root->val);
            maxdep = depth;
        } else
            ans[depth] = root->val;
        dfs(root->left, depth+1);
        dfs(root->right, depth+1);
       
    }
    
    vector<int> rightSideView(TreeNode* root) {
        maxdep = -1;
        dfs(root, 0);  
        return ans;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容