题目: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);
}
}