Simple C++ implementation


  • 0
    T
    class Solution {
    private:
        int treeHeight(TreeNode* root)
        {
            if(root == NULL)
                return 0;
            if(treeHeight(root->left) > treeHeight(root->right))
                return 1 + treeHeight(root->left);
            else
                return 1 + treeHeight(root->right);
        }
        
        void rightSideViewHelper(TreeNode* root, vector<int> &result, int depth)
        {
            if(root==NULL)
                return;
            result[depth-1] = root->val;
            rightSideViewHelper(root->left, result, depth+1);
            rightSideViewHelper(root->right, result, depth+1);
        }
    public:
        vector<int> rightSideView(TreeNode* root) {
            int n = treeHeight(root);
            vector<int> result;
            if(n==0)
                return result;
            result.resize(n);
            rightSideViewHelper(root, result, 1);
            return result;
        }
    };

Log in to reply
 

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