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; }}
新聞熱點(diǎn)
疑難解答