二叉树前序遍历java
时间: 2024-01-23 19:16:01 浏览: 69
以下是Java实现二叉树前序遍历的两种方法:
1. 递归方法:
```java
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
public class BinaryTree {
public void preorderTraversal(TreeNode root) {
if (root == null) {
return;
}
System.out.print(root.val + " "); // 先访问根节点
preorderTraversal(root.left); // 再访问左子树
preorderTraversal(root.right); // 最后访问右子树
}
}
// 创建二叉树
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);
// 调用前序遍历方法
BinaryTree binaryTree = new BinaryTree();
binaryTree.preorderTraversal(root); // 输出:1 2 4 5 3
```
2. 栈方法:
```java
import java.util.Stack;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
public class BinaryTree {
public void preorderTraversal(TreeNode root) {
if (root == null) {
return;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
System.out.print(node.val + " "); // 先访问根节点
if (node.right != null) {
stack.push(node.right); // 右子树入栈
}
if (node.left != null) {
stack.push(node.left); // 左子树入栈
}
}
}
}
// 创建二叉树
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);
// 调用前序遍历方法
BinaryTree binaryTree = new BinaryTree();
binaryTree.preorderTraversal(root); // 输出:1 2 4 5 3
```
阅读全文