zoukankan      html  css  js  c++  java
  • Binary Tree Right Side View

    Binary Tree Right Side View

    问题:

    Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

    For example:
    Given the following binary tree,

    思路:

      bfs+dfs

    我的代码:

    public class Solution {
        public List<Integer> rightSideView(TreeNode root) {
            List<Integer> rst = new ArrayList<Integer>();
            if(root == null) return rst;
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.offer(root);
            while(!queue.isEmpty())
            {
                int size = queue.size();
                for(int i = 0; i < size; i++)
                {
                    TreeNode node = queue.poll();
                    if(i == size-1)
                    {
                        rst.add(node.val);
                    }
                    if(node.left != null)
                        queue.offer(node.left);
                    if(node.right != null)
                        queue.offer(node.right);
                }
            }
            return rst;
        }
    }
    View Code

    他人代码:

    public class Solution {
        public List<Integer> rightSideView(TreeNode root) {
            List<Integer> result = new ArrayList<Integer>();
            rightView(root, result, 0);
            return result;
        }
    
        public void rightView(TreeNode curr, List<Integer> result, int currDepth){
            if(curr == null){
                return;
            }
            if(currDepth == result.size()){
                result.add(curr.val);
            }
    
            rightView(curr.right, result, currDepth + 1);
            rightView(curr.left, result, currDepth + 1);
    
        }
    }
    View Code

    学习之处:

    • 没有想到DFS的解法啊,看到别人怎么写的,思路真实精妙啊,可以通过层数控制只输出一侧。
  • 相关阅读:
    数列(codevs 1141)
    Circle(codevs 3134)
    Jam的计数法(codevs 1140)
    水果姐逛水果街Ⅰ(codevs 3304)
    引水入城(codevs 1066)
    Vigenère 密码(luogu 1079)
    铺地毯(luogu 1003)
    SSO之CAS基础及应用视频教程(1)
    Spark高速入门指南(Quick Start Spark)
    python爬虫CSDN文章抓取
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4458594.html
Copyright © 2011-2022 走看看