Java使用栈遍历树的代码
时间: 2024-05-08 12:19:58 浏览: 12
好的,以下是使用栈遍历二叉树的Java代码示例:
```
// 定义树的节点结构
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
// 使用栈遍历二叉树
public static 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);
}
}
}
```
上述代码实现了使用栈遍历二叉树的前序遍历,可以将 `System.out.print(node.val + " ");` 改为相应的代码实现中序或后序遍历。
相关问题
java遍历树形对象
在Java中,要遍历树形对象,可以使用递归或者栈数据结构来实现。下面是使用递归的示例代码:
```java
public class TreeNode {
private int value;
private List<TreeNode> children;
// 省略构造方法和其他方法
public void traverse() {
System.out.println(value); // 先输出当前节点的值
if (children != null) {
for (TreeNode child : children) {
child.traverse(); // 递归遍历子节点
}
}
}
}
```
使用上述代码,可以通过调用根节点的`traverse()`方法来遍历整个树形结构。
另外,如果你希望按照某种特定的顺序遍历树,比如前序、中序或后序遍历,你可以修改`traverse()`方法中的代码来满足需求。
树的遍历如何用java实现
在 Java 中,可以使用递归或迭代来遍历树。
递归遍历:
```java
public void traversePreOrder(TreeNode node) {
if (node == null) return;
// visit the node
traversePreOrder(node.left);
traversePreOrder(node.right);
}
```
这是先序遍历的代码。先序遍历顺序是:根节点、左子树、右子树。
迭代遍历:
```java
public void traversePreOrder(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
while (current != null || !stack.isEmpty()) {
if (current != null) {
// visit the node
stack.push(current);
current = current.left;
} else {
current = stack.pop();
current = current.right;
}
}
}
```
这是使用栈实现先序遍历的代码。
如果想要中序遍历或后序遍历,只需要改变访问节点的位置即可。例如,要改成中序遍历,就需要在遍历左子树之后访问节点,再遍历右子树。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)