国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

[LeetCode] Binary Tree Right Side View

2019-11-15 01:07:21
字體:
供稿:網(wǎng)友
[LeetCode] Binary Tree Right Side View

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

For example:Given the following binary tree,

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

You should return[1, 3, 4].

最近感覺做了好多和BTS有關(guān)的題哈哈。

這道題個人感覺難度還好。用兩個list來解決就好。一個用來store結(jié)果,另一個則是用來loop。

這道題其實(shí)就是寫一個算法從樹頭到數(shù)尾一一排查,只不過我們一定要想到有時候左邊長度會比右邊長,所以你在右邊,也是可以看到左邊的比右邊長的那部分的node的。所以我們不能只關(guān)注右側(cè)。

但算法運(yùn)行的時候我們肯定要先觀察右邊,所以往排查的list里面加元素的時候先add的一定是右邊的,這樣只要右邊有,那么最先看到的一定是右邊的那個。然后接下來再是左邊。這樣一想,就會簡單很多了。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<Integer> rightSideView(TreeNode root) {        ArrayList<Integer> result=new ArrayList<Integer>();        if(root==null){            return result;        }        LinkedList<TreeNode> count=new LinkedList<TreeNode>();        count.add(root);        while(count.size()>0){            int size=count.size();            for(int i=0;i<size;i++){                TreeNode test=count.remove();                if(i==0){                    result.add(test.val);                }                if(test.right!=null){                    count.add(test.right);                }                if(test.left!=null){                    count.add(test.left);                }            }        }        return result;    }}


發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 镇原县| 忻城县| 瑞金市| 万山特区| 武功县| 阳谷县| 林州市| 新源县| 饶平县| 于都县| 铜川市| 公安县| 镇宁| 洪雅县| 宁蒗| 天台县| 乌兰县| 体育| 双辽市| 华容县| 鲜城| 寿阳县| 万荣县| 剑河县| 林周县| 旺苍县| 都昌县| 浦东新区| 浙江省| 天峻县| 信阳市| 依兰县| 舟曲县| 浦城县| 静宁县| 青龙| 格尔木市| 凌云县| 抚州市| 阿拉善左旗| 山东|