1. 程式人生 > >[leetcode] Binary Tree Right Side View

[leetcode] Binary Tree Right Side View

dfs,記錄已經訪問到的層數即可。程式碼如下:

vector<int> rightSideView(TreeNode *root) {
        vector<int> result;
        int curLevel = 0, level = -1;
        dfs(result, curLevel, level, root);
        return result;
    }
    void dfs(vector<int> &result, int curLevel, int &level, TreeNode *root){
        if(!root)
            return;
        if(curLevel > level){
            result.push_back(root->val);
            ++level;
        }
        dfs(result, curLevel + 1, level, root->right);
        dfs(result, curLevel + 1, level, root->left);
    }