DFS Level Order Traversal Solution C++


  • 0
    A
    class Solution {
    public:
        vector<int> rightSideView(TreeNode* root) {
            vector<int> ans;
            
            if (root == NULL) {
                return ans;
            }
            
            int level = 0;
            
            TreeNode* it = root;
            DFS(ans, it, 0);
            
            return ans;
        }
        
        void DFS(vector<int> &ans, TreeNode *it, int level) {
            if (it == NULL)
                return;
                
            if (ans.size() > level)
                ans[level] = it->val;
            else
                ans.push_back(it->val);
                
            DFS(ans, it->left, level + 1);
            DFS(ans, it->right, level + 1);
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.