标题:Java实现二叉树的先序遍历含递归,非递归,Morris
public class TestMyTreeB {
public void preorder(IntNode p
) {
if(p
== null
) {
return ;
}else {
System
.out
.print(p
.val
+ " ");
this.preorder(p
.left
);
this.preorder(p
.right
);
}
}
public void preorder02(IntNode p
) {
Deque
<IntNode> s
= new LinkedList<>();
if(p
== null
) {
return ;
}
s
.push(p
);
while(!s
.isEmpty()) {
System
.out
.print(s
.peek().val
+ " ");
while(s
.peek().left
!= null
) {
IntNode node
= s
.peek().left
;
System
.out
.print(node
.val
+ " ");
s
.push(node
);
}
IntNode node
= s
.peek().right
;
s
.pop();
while(!s
.isEmpty() && node
== null
) {
node
= s
.peek().right
;
s
.pop();
}
if(node
!= null
){
s
.push(node
);
}
}
}
public void preorder03(IntNode p
) {
Deque
<IntNode> s
= new LinkedList<>();
if(p
== null
) {
return ;
}
s
.push(p
);
while(!s
.isEmpty()) {
System
.out
.print(s
.peek().val
+ " ");
IntNode node
= s
.pop();
if(node
.right
!= null
) {
s
.push(node
.right
);
}
if(node
.left
!= null
) {
s
.push(node
.left
);
}
}
}
@Test
public void test02() {
IntNode p1
= new IntNode('a');
IntNode p2
= new IntNode('b');
IntNode p3
= new IntNode('c');
IntNode p4
= new IntNode('d');
IntNode p5
= new IntNode('e');
IntNode p6
= new IntNode('f');
IntNode p7
= new IntNode('g');
IntNode p8
= new IntNode('h');
IntNode p9
= new IntNode('i');
IntNode p10
= new IntNode('j');
IntNode p11
= new IntNode('k');
p1
.left
= p2
;
p1
.right
= p3
;
p2
.left
= p4
;
p2
.right
= p5
;
p4
.right
= p6
;
p5
.left
= p7
;
p5
.right
= p8
;
p3
.left
= p9
;
p3
.right
= p10
;
p10
.right
=p11
;
System
.out
.println("递归的先序遍历");
this.preorder(p1
);
System
.out
.println();
System
.out
.println("测试非递归先序遍历");
this.preorder02(p1
);
System
.out
.println();
System
.out
.println("测试非递归先序遍历 【树上的】");
this.preorder03(p1
);
System
.out
.println();
}
}
转载请注明原文地址: https://lol.8miu.com/read-36470.html