[leetcode]199. Binary Tree Right Side View

虽然只保留右节点,但是左节点也要向下遍历,因为可能到某一层,要用到左节点,所以要用一个数据结构记录本层有没有记录,如果记录过了就不用记录,向下遍历就行,没有记录就记录。递归的时候要同时记录层数

先dfs右节点,再左节点

List<Integer> res = new ArrayList<>();
    public List<Integer> rightSideView(TreeNode root) {
        helper(root, new ArrayList<>(),0);
        return res;
    }
    public void helper(TreeNode root,List<Boolean> list,int cur)
    {
        if (root==null)
            return;
        if (list.size()==cur)
            list.add(false);
        if (!list.get(cur))
        {
            res.add(root.val);
            list.add(cur,true);
        }
        helper(root.right,list,cur+1);
        helper(root.left,list,cur+1);
    }
原文地址:https://www.cnblogs.com/stAr-1/p/8351334.html