void rightViewUtil(TreeNode* root, int level) { if (!root) return; if (level > max_level) { res.push_back(root->val); max_level = level; } rightViewUtil(root->right,level+1); rightViewUtil(root->left,level+1); }
// Recursive function to print right view of a binary tree. void rightViewUtil(struct Node *root, int level, int *max_level) { // Base Case if (root==NULL) return; // If this is the first Node of its level if (*max_level < level) { printf("%d\t", root->data); *max_level = level; } // Recur for right subtree first, then left subtree rightViewUtil(root->right, level+1, max_level); rightViewUtil(root->left, level+1, max_level); }
vector<int> rightSideView(TreeNode* root) { if (!root) { return res; } rightViewUtil(root,0); return res; }
// A wrapper over rightViewUtil() void rightView(struct Node *root) { int max_level = 0; rightViewUtil(root, 1, &max_level); }