标签:
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; } };
LeetCode "Binary Tree Right Side View"
标签:
原文地址:http://www.cnblogs.com/tonix/p/4421726.html