199. 二叉树的右视图 + 宽度优先搜索 + 深度优先搜索

199. 二叉树的右视图

LeetCode_199

题目描述

方法一:使用宽度优先搜索(类似于层次遍历,每次记录最后一个元素)

/**
 * 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 {
    public List<Integer> rightSideView(TreeNode root) {
        Queue<TreeNode> que = new LinkedList<>();
        List<Integer> result = new ArrayList<>();
        if(root == null)
            return result;
        que.offer(root);
        while(!que.isEmpty()){
            int size = que.size();
            for(int i=que.size(); i>0; i--){
                TreeNode now = que.poll();
                if(i == 1){
                    result.add(now.val);
                }
                if(now.left != null)
                    que.offer(now.left);
                if(now.right != null)
                    que.offer(now.right);
            }
        }
        return result;
    }
}

方法二:使用深度优先搜索

class Solution {
    List<Integer> result = new ArrayList<>();
    public List<Integer> rightSideView(TreeNode root) {
        dfs(root, 0);
        return result;
    }
    public void dfs(TreeNode root, int depth){
        if(root == null)
            return;
        //如果当前深度和结果列表中的元素个数一样,说明这是当前层第一个遍历的元素,且每一层保证了只进一个结点
        if(depth == result.size()){
            result.add(root.val);
        }
        dfs(root.right, depth + 1);//先遍历右子树,保证右边的结点最先遍历
        dfs(root.left, depth + 1);//再遍历左子树
    }
}
posted @ 2021-03-14 10:32  Garrett_Wale  阅读(87)  评论(0编辑  收藏  举报