• leetcode 199 二叉树的右视图


    简介

    常规方法, BFS

    code

    这里使用了隔板法, 其实有概率出错的.

    class Solution {
    public:
        vector<int> rightSideView(TreeNode* root) {
            // bfs
            queue<TreeNode*> q;
            vector<int> rlt;
            if(root == nullptr){
                return rlt;
            }
            q.push(root);
            TreeNode * p = new TreeNode(1e9);
            q.push(p);
            
            while(!q.empty()){
                TreeNode* t = q.front();
                q.pop();
    
                if(t->left){
                    q.push(t->left);
                }
                if(t->right){
                    q.push(t->right);
                }
                if(q.front()->val == 1e9){
                    rlt.push_back(t->val);
                    q.pop();
                    if(q.empty()){
                        break;
                    }
                    q.push(p);
                }
            }
            return rlt;
        }
    };
    
    class Solution {
        List<Integer> res = new ArrayList<>();
    
        public List<Integer> rightSideView(TreeNode root){
            dfs(root, 0);
            return res;
        }
        private void dfs(TreeNode root, int depth) {
            if(root == null) {
                return;
            }
            // 先访问当前节点, 再递归地访问右子树和左子树
            if(depth == res.size()) {
                res.add(root.val);
            }
            depth++;
            dfs(root.right, depth);
            dfs(root.left, depth);
        }
    }
    

    java 的思路很巧妙, dfs, 时间和效率都较快.
    if(depth == res.size()) {
    res.add(root.val);
    }
    这一部分很巧妙, 每一层的最先被遍历到的节点放入了dfs中. 其他的被排除了, 根右左的遍历方式.

    Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
  • 相关阅读:
    varnish4.X安装
    关于varnish缓存
    s3cmd的使用
    MarkdownPad 2
    Lua控制语句
    Lua表达式
    后端怎么防止重复提交?(常用的做法)
    Redis用setnx+expire实现分布式锁存在什么隐患,如何改进?
    推送消息为什么使用RocketMQ,而不使用Kafka?
    自定义线程池,如何最佳创建线程池
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/14774796.html
Copyright © 2020-2023  润新知