zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 199 二叉树的右视图

    199. 二叉树的右视图

    给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

    示例:

    输入: [1,2,3,null,5,null,4]
    输出: [1, 3, 4]
    解释:

       1            <---
     /   
    2     3         <---
          
      5     4       <---
    

    PS:

    1层序遍历

    2递归

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution { 
      public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<>();
            if(root == null) return res;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            while(!queue.isEmpty()){
                int count = queue.size();
                while(count > 0){
                    count--;
                    TreeNode cur = queue.poll();
                    if(count == 0){
                        //只有上一层的最后一个才能加入res
                        //如果右面有,就是右面
                        //右面没有,左面就是上一层的最后一个
                        res.add(cur.val);
                    }
                    //先加左面,先poll左面
                    if(cur.left != null){
                        queue.add(cur.left);
                    }
                    if(cur.right != null){
                        queue.add(cur.right);
                    }
                }
            }
            return res;
      }
     
    }
    
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
       int[] max = {0};
      public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        helper(res, root, 1);
        return res;
      }
    
      private void helper(List<Integer> res,TreeNode treeNode, int deep) {
        if (treeNode == null) {
          return;
        }
        if (deep > max[0]) {
          max[0] = deep;
          res.add(treeNode.val);
        }
        helper(res, treeNode.right, deep + 1);
        helper(res, treeNode.left, deep + 1);
      }
    }
    
  • 相关阅读:
    next_permutation
    P1087 FBI树
    P4047 [JSOI2010]部落划分
    买礼物
    P2121 拆地毯
    Nebula Graph 在大规模数据量级下的实践和定制化开发
    深入了解kafka系列-消费者
    一分钟教你搭建WebRTC流媒体服务器Janus-gateway
    什么是"前端工程化"?
    斗鱼Juno 监控中心的设计与实现
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13075419.html
Copyright © 2011-2022 走看看