199. 二叉树的右视图:
题目链接 :199. 二叉树的右视图
题目:
给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
思路:
1、BFS
(1)广度优先:对树的每层进行根-左-右的顺序遍历存入队列
(2)那么每层最后一个入队的元素就是我们需要的最右元素
(3)进行N层遍历,N==队列.size()
2、DFS
(1)深度优先:依照根右左的顺序遍历,保证右子树先入队
(2)设定深度值,即标识当前层数
(3)又因为保证了根左右的顺序,所以我们将每个深度值第一次出现时对应的最右侧元素记录
AC代码:
- BFS
class Solution {
private List<Integer> ans = new ArrayList<>();
public List<Integer> rightSideView(TreeNode root) {
if(root == null) return ans;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
int len = queue.size(); // 每层元素的数量
for(int i = 0 ; i < len ; ++i){
TreeNode curr = queue.poll();
if(curr.left != null) queue.offer(curr.left);
if(curr.right != null) queue.offer(curr.right);
if(i == len - 1) ans.add(curr.val);
}
}
return ans;
}
}
- DFS
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
List<Integer> ans=new LinkedList<>();
public List<Integer> rightSideView(TreeNode root) {
dfs(root,0);
return ans;
}
private void dfs(TreeNode root ,int depth)
{
if(root==null)
{
return;
}if(depth==ans.size())
ans.add(root.val);
depth++;
dfs(root.right,depth);
dfs(root.left,depth);
}
}