题目描述
给定一个二叉树的根节点 root
,返回 它的 中序 遍历 。
示例 1:
输入:root = [1,null,2,3] 输出:[1,3,2]
示例 2:
输入:root = [] 输出:[]
示例 3:
输入:root = [1] 输出:[1]
示例 4:
输入
root =[1,2,3,4,5,null,8,null,null,6,7,9]
输出
[4,2,6,5,7,1,3,9,8]
代码思路:
java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list =new ArrayList();
midsort(root,list);
return list;
}
public void midsort(TreeNode root,List<Integer> list){
if(root!=null){
midsort(root.left,list);
list.add(root.val);
midsort(root.right,list);
}
}
}