码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 199. 二叉树的右视图(Binary Tree Right Side View)

时间:2019-05-19 20:41:51      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:res   core   one   参考资料   nod   tree   ide   null   dev   

199. 二叉树的右视图
199. 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.

LeetCode199. Binary Tree Right Side View

示例:

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

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

The core idea of this algorithm:

  1. Each depth of the tree only select one node.
  2. View depth is current size of result list.

Java 实现

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}
import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        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);
    }
}

相似题目

参考资料

LeetCode 199. 二叉树的右视图(Binary Tree Right Side View)

标签:res   core   one   参考资料   nod   tree   ide   null   dev   

原文地址:https://www.cnblogs.com/hglibin/p/10890586.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!