在Java中,优化TreeNode的遍历可以通过以下几种方法实现:
import java.util.LinkedList;
import java.util.Queue;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public void inorderTraversal(TreeNode root) {
if (root == null) {
return;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode currentNode = queue.poll();
// 处理当前节点
System.out.print(currentNode.val + " ");
// 将右子节点和左子节点按顺序加入队列
if (currentNode.right != null) {
queue.offer(currentNode.right);
}
if (currentNode.left != null) {
queue.offer(currentNode.left);
}
}
}
public void morrisTraversal(TreeNode root) {
TreeNode currentNode = root;
while (currentNode != null) {
if (currentNode.left == null) {
// 处理当前节点
System.out.print(currentNode.val + " ");
currentNode = currentNode.right;
} else {
// 找到当前节点左子树的最右节点
TreeNode predecessor = currentNode.left;
while (predecessor.right != null && predecessor.right != currentNode) {
predecessor = predecessor.right;
}
if (predecessor.right == null) {
// 将当前节点左子树的最右节点的右指针指向当前节点
predecessor.right = currentNode;
currentNode = currentNode.left;
} else {
// 恢复树的结构并移动到右子树
predecessor.right = null;
// 处理当前节点
System.out.print(currentNode.val + " ");
currentNode = currentNode.right;
}
}
}
}
import java.util.List;
import java.util.stream.Collectors;
public List<TreeNode> trees = // ... 初始化多个树结构
trees.parallelStream().forEach(this::inorderTraversal);
通过以上方法,可以根据具体的应用场景和需求选择合适的优化策略,以提高TreeNode的遍历效率。