package tree;
public class InorderTree {
/**
* 不带栈的二叉树中序非递归遍历
* 1. Initialize current as root
2. While current is not NULL
If current does not have left child
a) Print current’s data
b) Go to the right, i.e., current = current->right
Else
a) Make current as right child of the rightmost node in current's left subtree
b) Go to this left child, i.e., current = current->left
* @param args
*/
public static void printinorderTree(TreeNode root){
TreeNode current = root;
while(current!=null){
if(current.left==null){
System.out.print(current.value+" ");
current = current.right;
}else{
TreeNode node = current.left;
while(node.right!=null&&node.right!=current){
node = node.right;
}
if(node.right==null){
node.right = current;
current = current.left;
}else{
System.out.print(current.value+" ");
node.right = null;
current = current.right;
}
}
}
}
public static void main(String[] args) {
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);
printinorderTree(root);
}
}
不带栈的二叉树中序非递归遍历
最新推荐文章于 2022-06-01 21:55:16 发布