Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
    }
};
posted on 2015-04-13 11:28  Tonix  阅读(166)  评论(0编辑  收藏  举报