題目: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.
解題思路:
1. 右子樹的高度 >= 左子樹 , easy ;
2. 左子樹 > 右子樹?
3. 通過層序遍歷(BFS),每一層的最右邊加入結果鏈表;
/**
* 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> list = new ArrayList<Integer> ();
LinkedList<TreeNode> queue = new LinkedList<TreeNode> ();
//當前層節點個數,下一層節點個數
int curCount , nextCount = 0;
if(root == null) return list;
queue.add(root);
curCount = 1;
list.add(root.val);
while(!queue.isEmpty()) {
if(curCount == 0) {
curCount = nextCount;
// 注意這裏一定要置0
nextCount = 0;
list.add(queue.getLast().val);
}
TreeNode node = queue.removeFirst();
curCount--;
if(node.left != null) {
queue.add(node.left);
nextCount++;
}
if(node.right != null) {
queue.add(node.right);
nextCount++;
}
}
return list;
}
}
DFS(前序遍歷)解題
- 因爲每一層都必然有一個會有一個值添加到返回鏈表中;
- 這樣我們只要比較返回鏈表的大小與當前的深度,如果小於,則添加到鏈表
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
help(root, 1, result);
return result;
}
public void help(TreeNode root, int depth, List<Integer> result) {
if (root == null)
return;
if (result.size() < depth)
result.add(root.val);
// 從右子樹開始!
help(root.right, depth + 1, result);
help(root.left, depth + 1, result);
}
}