二叉树的中序遍历
描述
给定一个二叉树的根节点root,返回它的中序遍历。
解题
二叉树
public class TreeNode{
int val;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val){
this.val=val;
}
}
Solution
/**
* 递归中序遍历,列表
*/
import java.util.ArrayList;
import java.util.List;
public class Solution {
public int[] inorderTraversal (TreeNode root){
List<Integer> list = new ArrayList<>();//创建列表
help(root,list);//中序遍历
//return list.stream().mapToInt(Integer::valueOf).toArray();
int [] arr=new int[list.size()];//Integer[]转int[]
for(int i=0;i<list.size();i++){
arr[i]=list.get(i);
}
return arr;
}
private void help(TreeNode root, List<Integer> list){
if (root==null) return;
help(root.left,list);
list.add(root.val);
help(root.right,list);
}
}