leetbook:中级算法
类型:树和图
题目名:二叉树的中序遍历
原题URL:https://leetcode-cn.com/leetbook/read/top-interview-questions-medium/xv7pir/
题目描述
给定一个二叉树的根节点 root
,返回它的 中序 遍历。
示例
示例 1:
输入:root = [1,null,2,3]
输出:[1,3,2]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
限制
- 树中节点数目在范围
[0, 100]
内 -100 <= Node.val <= 100
解题思路
树里面最基本的题,就是中序遍历,前序遍历,后续遍历,直接递归解决
解题代码
/**
* 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 {
List<Integer> res = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if(root==null) return res;
inorder(root);
return res;
}
public void inorder(TreeNode root) {
if(root==null) return;
if(root.left!=null) inorder(root.left);
res.add(root.val);
if(root.right!=null) inorder(root.right);
}
}