二叉树的遍历java递归
时间: 2023-11-12 08:54:55 浏览: 76
二叉树的遍历有三种方式:前序遍历、中序遍历和后序遍历。下面是使用Java递归进行二叉树遍历的代码示例:
前序遍历:
```java
import java.util.ArrayList;
import java.util.List;
public class Solution {
public static void main(String[] args) {
TreeNode node1 = new TreeNode(1);
node1.right = new TreeNode(3);
Solution sol = new Solution();
System.out.println(sol.preorderTraversal(node1));
}
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
preOrder(list, root);
return list;
}
public void preOrder(List<Integer> list, TreeNode root) {
if (root == null) {
return;
}
list.add(root.val);
preOrder(list, root.left);
preOrder(list, root.right);
}
}
```
中序遍历:
```java
import java.util.ArrayList;
import java.util.List;
public class Solution {
public static void main(String[] args) {
Solution sol = new Solution();
TreeNode node1 = new TreeNode(1);
node1.left = new TreeNode(2);
node1.right = new TreeNode(3);
node1.right.left = new TreeNode(4);
System.out.println(sol.inorderTraversal(node1));
}
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
inOrder(list, root);
return list;
}
public void inOrder(List<Integer> list, TreeNode root) {
if (root == null) {
return;
}
inOrder(list, root.left);
list.add(root.val);
inOrder(list, root.right);
}
}
```
后序遍历:
```java
import java.util.ArrayList;
import java.util.List;
public class Solution {
public static void main(String[] args) {
Solution sol = new Solution();
TreeNode node = new TreeNode(1);
node.left = new TreeNode(2);
node.right = new TreeNode(3);
System.out.println(sol.postorderTraversal(node));
}
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
postOrder(list, root);
return list;
}
public void postOrder(List<Integer> list, TreeNode root) {
if (root == null) {
return;
}
postOrder(list, root.left);
postOrder(list, root.right);
list.add(root.val);
}
}
```
阅读全文