码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Binary Tree Right Side View"

时间:2015-04-13 12:22:37      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!