题目描述:给定一个二叉树的根节点 ,返回 它的 中序 遍历 。root
获得更多?算法思路:代码文档,算法解析的私得。
运行效果
完整代码
import java.util.ArrayList;
import java.util.List;
/**
* 2 * @Author: LJJ
* 3 * @Date: 2023/8/14 14:09
* 4
*/
public class InorderTraversal {
static class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode (int val){
this.val = val;
}
}
public List<Integer> inorderTraversal(TreeNode root){
List<Integer> result = new ArrayList<>();
inorderHelper(root,result);
return result;
}
private void inorderHelper(TreeNode node, List<Integer> result){
if (node == null){
return;
}
inorderHelper(node.left,result); // 遍历左子树
result.add(node.val);
inorderHelper(node.right,result); //遍历右子树
}
public static void main(String[] args) {
// 构建二叉树
TreeNode root = new TreeNode(1);
root.right = new TreeNode(2);
root.left = new TreeNode(2);
root.right.left = new TreeNode(3);
root.right.right = new TreeNode(4);
root.left.left = new TreeNode(5);
root.left.right = new TreeNode(7);
root.left.left.right = new TreeNode(8);
// 创建中序遍历对象
InorderTraversal inorderTraversal = new InorderTraversal();
// 调用中序遍历函数,传入根节点
List<Integer> result = inorderTraversal.inorderTraversal(root);
// 打印中序遍历结果
System.out.println(result);
}
}