题目199. Binary Tree Right Side View
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,深搜
思路: 深搜,一个集合中存放访问到的每层节点,在搜索的过程中,更新对应层的最右边节点
public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
dfs(root,result,0);
return result;
}
private void dfs(TreeNode root, List<Integer> result, int level){
if(root == null){
return;
}
if(result.size() == level){
result.add(level,root.val);
}else{
result.set(level,root.val);
}
dfs(root.left,result,level+1);
dfs(root.right,result,level+1);
}
2,利用层次遍历
思路:利用层次遍历, 然后每层遍历结束后,取最右边的节点
public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
if(root == null){
return result;
}
Stack<TreeNode> curLevelNodes = new Stack<TreeNode>();
curLevelNodes.push(root);
while(!curLevelNodes.empty()){
TreeNode rightNode = curLevelNodes.peek();
result.add(rightNode.val);
Stack<TreeNode> nextLevelNodes = new Stack<TreeNode>();
for(TreeNode node : curLevelNodes){
if(node.left != null){
nextLevelNodes.add(node.left);
}
if(node.right != null){
nextLevelNodes.add(node.right);
}
}
curLevelNodes = nextLevelNodes;
}
return result;
}