zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    委托使用不当导致内存变大
    Reactive Extension
    WPF TextBox输入显示提示
    Reactive Extensions 初识
    WPF 验证
    SPOJ 1487. Query on a tree III
    HDU3966 Aragorn's Story
    SPOJ 2939. Query on a tree V
    SPOJ 913. Query on a tree II
    SPOJ2666. Query on a tree IV
  • 原文地址:https://www.cnblogs.com/tonix/p/4421726.html
Copyright © 2011-2022 走看看