binary tree 的inorder 和preorder 和postorder
时间: 2024-11-01 16:08:08 浏览: 1
Binary_Tree_Level_Order_Traversa
In-order, pre-order, and post-order traversals are methods to visit each node in a binary tree in a specific sequence.
1. **In-order traversal**[^1]: Also known as the "left-root-right" order, it visits the left subtree first, then the root node, and finally the right subtree. This ensures that for a binary search tree, the output will be sorted.
```java
// Example for In-order traversal
void inorderTraversal(TreeNode root) {
if (root != null) {
inorderTraversal(root.left);
System.out.print(root.val + " "); // Visit the current node
inorderTraversal(root.right);
}
}
```
2. **Pre-order traversal**: The "root-left-right" order, starts by visiting the root, followed by the left subtree, and then the right subtree.
```java
// Example for Pre-order traversal
void preorderTraversal(TreeNode root) {
if (root != null) {
System.out.print(root.val + " "); // Visit the current node first
preorderTraversal(root.left);
preorderTraversal(root.right);
}
}
```
3. **Post-order traversal**: The "left-right-root" order, visits the left subtree, then the right subtree, and finally the root node.
```java
// Example for Post-order traversal
void postorderTraversal(TreeNode root) {
if (root != null) {
postorderTraversal(root.left);
postorderTraversal(root.right);
System.out.print(root.val + " "); // Visit the current node last
}
}
```
阅读全文