LeetCode94. 二叉树的中序遍历

275 阅读1分钟

给定一个二叉树的根节点 root ,返回它的 中序 遍历。

示例 1:

输入:root = [1,null,2,3]
输出:[1,3,2]

示例 2:

输入:root = []
输出:[]

示例 3:

输入:root = [1]
输出:[1]

提示:

树中节点数目在范围 [0, 100] 内
-100 <= Node.val <= 100

树的中序遍历,递归:

  • 1. 若根节点为空,直接返回
  • 2. 若左子树不为空,递归遍历左子树
  • 3. 将根节点的val加入结果集合
  • 4. 若右子树不为空,递归遍历右子树

class Solution { 
    List res = new ArrayList<>();
public List inorderTraversal(TreeNode root) {
if(root == null){
return res;
}
if(root.left != null){
inorderTraversal(root.left);
}
res.add(root.val);
if(root.right != null){
inorderTraversal(root.right);
}
return res;
}
}