目录
- 题目描述:
- 输入:
- 输出:
- 代码实现:
题目描述:
给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。
输入:
root = [1,null,2,3]
输出:
[1,3,2]
代码实现:
新建一个树结点类:
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;}
}
主函数:
import java.util.ArrayList;
import java.util.List;public class Main{public static void main(String[] args) {//构建二叉树TreeNode root = new TreeNode(1,null,new TreeNode(2,new TreeNode(3),null));//调用函数List<Integer> list = inorderTraversal(root);System.out.println(list);}public static List<Integer> inorderTraversal(TreeNode root) {List<Integer> list = new ArrayList<>();//创建动态数组返回结果inOrder(root, list);//递归调用return list;}private static void inOrder(TreeNode root, List<Integer> list) {if (root == null) {//如果当前结点为空,则结束本轮递归return;}//遍历左子树inOrder(root.left, list);//遍历当前根结点list.add(root.val);//遍历右子树inOrder(root.right, list);}
}