LeetCode "Binary Tree Right Side View"

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;
    }
};

转载于:https://www.cnblogs.com/tonix/p/4421726.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值