中序遍历的顺序是:先访问左子树,再访问根节点,最后访问右子树。
class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; this.left = null; this.right = null; } } public class InorderTraversal { // 递归实现中序遍历 public static void inorderTraversal(TreeNode root) { if (root == null) { return; } // 递归访问左子树 inorderTraversal(root.left); // 访问根节点 System.out.print(root.val + " "); // 递归访问右子树 inorderTraversal(root.right); } public static void main(String[] args) { // 创建一个简单的二叉树 // 1 // / \ // 2 3 // / \ // 4 5 TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); root.left.left = new TreeNode(4); root.left.right = new TreeNode(5); System.out.println("中序遍历结果:"); inorderTraversal(root); } }
标签:遍历,TreeNode,val,中序,right,二叉树,new,root,left From: https://www.cnblogs.com/Jomini/p/18358772