题目考察的知识点

考察二叉树的深度优先搜索以及对于题目的理解

题目解答方法的文字分析

这道题目其实要求的就是从左到右的叶子节点的序列,所以直接先序遍历将叶子节点存储起来就可以了。

本题解析所用的编程语言

使用Java解答

完整且正确的编程代码

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整型一维数组
     */
    ArrayList<Integer> list = new ArrayList<>();

    public int[] bottomView (TreeNode root) {
        // write code here
        dfs(root);
        int[] res = new int[list.size()];
        for(int i=0; i<list.size(); i++){
            res[i] = list.get(i);
        }
        return res;
    }

    public void dfs(TreeNode root){
        if(root==null) return;
        if(root.left==null&&root.right==null){
            list.add(root.val);
        }
        dfs(root.left);
        dfs(root.right);
    }
}