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 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 rightSideView(TreeNode* root) {
        maxdep = -1;
        dfs(root, 0);  
        return ans;
    }
};

你可能感兴趣的:(199. Binary Tree Right Side View)