zoukankan      html  css  js  c++  java
  • Leetcode 199. 二叉树的右视图

    题目链接

    https://leetcode.com/problems/binary-tree-right-side-view/description/

    题目描述

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

    示例:

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

    题解

    采用递归的方式求解。记录当前最大深度,如果遍历到的结点的深度大于最大深度,就加入到List。

    代码

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int depth = -1;
        public List<Integer> rightSideView(TreeNode root) {
            List<Integer> list = new ArrayList<>();
            backtrack(root, list, 0);
            return list;
        }
        
        public void backtrack(TreeNode root, List<Integer> list, int level) {
            if (root == null) { return ;}
            if (level > depth) {
                list.add(root.val);
                depth = level;
            }
            backtrack(root.right, list, level + 1);
            backtrack(root.left, list, level + 1);
        }
    }
    
    
  • 相关阅读:
    流程控制语句
    lminus
    TCL create list from file
    DFT 问答 III
    DFT 问答 II
    DFT 问答 I
    猜字符小游戏
    用户模式构造
    基元线程同步构造
    七大原则,24种设计模式
  • 原文地址:https://www.cnblogs.com/xiagnming/p/9667429.html
Copyright © 2011-2022 走看看