知识点

树,中序遍历

解题思路

这道题的题目意思就是让我们将树从小到大放到数组里面返回,而树又是二叉搜索树,所以我们只需要中序遍历树,将树的值放到list集合里面,再将list集合转换成数组返回就行。

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整型一维数组
     */
     List<Integer> list = new ArrayList<>();
    public int[] inorderTraversal (TreeNode root) {
        // write code here
        fun(root);
        return list.stream().mapToInt(Integer::intValue).toArray();
    }

    public void fun(TreeNode root){
        if(root.left != null){
            fun(root.left);
        }
        list.add(root.val);
        if(root.right != null){
            fun(root.right);
        }
    }
}