From 72141441cbd4d0755989e457d39dc91417d5674f Mon Sep 17 00:00:00 2001 From: 8ga Date: Fri, 10 Jan 2025 11:15:26 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20InOrderTraversal.java?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- InOrderTraversal.java | 78 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 InOrderTraversal.java diff --git a/InOrderTraversal.java b/InOrderTraversal.java new file mode 100644 index 0000000..88f80f4 --- /dev/null +++ b/InOrderTraversal.java @@ -0,0 +1,78 @@ +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +public class InOrderTraversal { + + public static void main(String[] args) { + 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); + + List result = inOrderTraversal(root); + System.out.println(result); // 输出: [4, 2, 5, 1, 3] + + List result2 = inOrderTraversalNonRecursive(root); + System.out.println(result2); // 输出: [4, 2, 5, 1, 3] + } + + // 中序遍历二叉树 + public static class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } + } + + // 递归中序遍历方法 + public static List inOrderTraversal(TreeNode root) { + List result = new ArrayList<>(); + forEach(root, result); + return result; + } + + public static void forEach(TreeNode node, List result) { + if (node != null) { + // 左子树 + forEach(node.left, result); + // 处理节点数据 + result.add(node.val); + // 右子树 + forEach(node.right, result); + } + } + + // 非递归中序遍历方法 + public static List inOrderTraversalNonRecursive(TreeNode root) { + if (root == null) { + return null; + } + + Stack stack = new Stack<>(); + TreeNode current = root; + List result = new ArrayList<>(); + + while (current != null || !stack.isEmpty()) { + // 将当前节点的所有左子节点压入栈中 + while (current != null) { + stack.push(current); + current = current.left; + } + // 弹出栈顶并访问 + current = stack.pop(); + result.add(current.val); + // 转向右子树 + current = current.right; + } + + return result; + } + +}