线索化遍历优点在于不需要递归和栈,空间复杂度降到O(1),且时间复杂度仍未O(n)。
期间会暂时修改树的数据结构,遍历结束后恢复。
线索化中序遍历二叉树
public void morrisTraversal(TreeNode root){
TreeNode temp = null;
while(root!=null){
if(root.left!=null){
// connect threading for root
temp = root.left;
while(temp.right!=null && temp.right != root)
temp = temp.right;
// the threading already exists
if(temp.right!=null){
temp.right = null;
System.out.println(root.val);
root = root.right;
}else{
// construct the threading
temp.right = root;
root = root.left;
}
}else{
System.out.println(root.val);
root = root.right;
}
}
}

本文介绍了一种不需要递归和栈的空间复杂度为O(1)的线索化二叉树遍历方法,通过临时修改树的数据结构来实现中序遍历,并在遍历结束后恢复原状。
4586

被折叠的 条评论
为什么被折叠?



