199 Binary Tree Right Side View
阿新 • • 發佈:2018-12-31
題目:
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.
For example:
Given the following binary tree,
1 <---
/ \
2 3 <---
\ \
5 4 <---
You should return [1, 3, 4].
解題思路:
這題的考點是樹的層次遍歷的變形。
1. 從右往左看去,能看到的每層的結點就是該層最右的結點,該層其它結點都被最右結點擋住了。
2. 解法就是層次遍歷每一層,每一層的最右結點就是要找的結點。
3. 即,使用一個佇列儲存樹的一層結點,將每一層最右結點放到結果連結串列中。
具體程式碼實現,採用兩個佇列,一個佇列放上一層的結點,一個佇列放當前層的結點。
也可以只採用一個佇列,此時只用記住每一層的結點個數,即可將一個佇列中的結點切分為父結點層和子結點層。
程式碼實現:
採用兩個佇列:
/**
* 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) {
List<Integer> res = new ArrayList();
if(root == null)
return res;
LinkedList<TreeNode> father = new LinkedList();
father.add(root);
res.add(root.val);
while (!father.isEmpty()) {
LinkedList<TreeNode> children = new LinkedList();
while(!father.isEmpty()) {
TreeNode r = father.poll();
if(r.left != null)
children.add(r.left);
if(r.right != null)
children.add(r.right);
}
if(!children.isEmpty()) {
father = children;
res.add(father.peekLast().val);
}
}
return res;
}
}
210 / 210 test cases passed.
Status: Accepted
Runtime: 3 ms
只採用一個佇列:
/**
* 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> queue = new LinkedList<TreeNode>();
queue.add(root);
while(queue.size() > 0){
//get size here
int size = queue.size();
for(int i=0; i<size; i++){
TreeNode top = queue.remove();
//the first element in the queue (right-most of the tree)
if(i==0){
result.add(top.val);
}
//add right first
if(top.right != null){
queue.add(top.right);
}
//add left
if(top.left != null){
queue.add(top.left);
}
}
}
return result;
}
}
210 / 210 test cases passed.
Status: Accepted
Runtime: 3 ms