I saw a lot of BFS based solutions. And my alternative solution is this mirror-ed BST iterator one, with some book-keeping:
class Solution { public: typedef pair<TreeNode*, int> Rec; vector<int> rightSideView(TreeNode *root) { vector<int> v; if (!root) return v; stack<Rec> stk; // int max_d = 0; TreeNode *p = root; while (p) { stk.push(Rec(p, ++max_d)); v.push_back(p->val); p = p->right; } // while (!stk.empty()) { Rec p0 = stk.top(); stk.pop(); if (p0.first->left) { TreeNode *pl = p0.first->left; int myd = p0.second; while (pl) { stk.push(Rec(pl, ++ myd)); if (myd > max_d) { v.push_back(pl->val); max_d = myd; } pl = pl->right; } }// if } return v; } };
Or, a much simpler one, i saw it from discussion panel:
class Solution { vector<int> v; public: void dfs(TreeNode *root, int l) { if (!root) return; if (l == v.size()) v.push_back(root->val); dfs(root->right, l + 1); dfs(root->left, l + 1); } vector<int> rightSideView(TreeNode *root) { if (!root) return v; dfs(root, 0); return v; } };