解题思路:直接将数按照中序遍历放到集合里,然后将集合转成int数组返回,需要遍历整个二叉树,而且需要集合来保存二叉树的值,故时间复杂度为O(n),空间复杂度为O(n)
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[] inorderTraversal (TreeNode root) {
// write code here
if (root == null) {
return new int[0];
}
ArrayList<Integer> list = new ArrayList<>();
addToList(root, list);
return list.stream().mapToInt(x->x).toArray();
}
private void addToList(TreeNode root, ArrayList<Integer> list) {
//中序遍历 左根右
if (root == null) {
return ;
}
addToList(root.left, list);
list.add(root.val);
addToList(root.right, list);
}
}
扩展:也可以使用非递归的方式来实现
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[] inorderTraversal (TreeNode root) {
// write code here
if (root == null) {
return new int[0];
}
ArrayList<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (!stack.isEmpty() || cur != null) {
if (cur != null) {
stack.push(cur);
cur = cur.left;
} else {
TreeNode node = stack.pop();
list.add(node.val);
cur = node.right;
}
}
return list.stream().mapToInt(x->x).toArray();
}
}