中序遍历:左节点->根节点->右节点
我采用的是递归的方法
题目是要求返回数组,我这里采用链表添加,之后转化成数组,代码中有相关注释
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> arrayList=new ArrayList<Integer>();
public int[] inorderTraversal (TreeNode root) {
// write code here
DiGui(root);//调用递归方法
int n=arrayList.size();
Integer[] temp=arrayList.toArray(new Integer[n]);//因为toArray转变的是对象,所以要创建Integer对象数组
int[] count=new int[n];
for (int i = 0; i < n; i++) {//要转换成int数组只能循环赋值
count[i]=temp[i];
}
return count;
}
void DiGui(TreeNode root){
if (root==null)
return;
DiGui(root.left);
arrayList.add(root.val);
DiGui(root.right);
}
} 
京公网安备 11010502036488号