import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型一维数组
     */
    public int[] bottomView (TreeNode root) {
        // write code here
        List<Integer> list = new ArrayList<>();
        preOrder(root, list);
        return list.stream().mapToInt(i -> i).toArray();
    }
    private void preOrder(TreeNode root, List<Integer> list) {
        if (root == null) return;
        if (root.left == null && root.right == null) list.add(root.val);
        preOrder(root.left, list);
        preOrder(root.right, list);
    }
}
  • 根据题意,需要求解二叉树的所有叶子节点集合 list,并且是从左至右
  • 利用 前序、中序、后续 遍历都可以
  • 遍历到根节点时,进行判断是否是叶子节点,如果是就加入到集合 list 中
  • 最后转换集合 list 为数组返回结果