
S型打印二叉树?
//S型层次遍历
public void levelSOrder(BinaryTreeNode p){
Stack<BinaryTreeNode> stack1 = new Stack<>();
Stack<BinaryTreeNode> stack2 = new Stack<>();
int currentLevel = 1;
if(p != null){
stack1.push(p);
}
while(!stack1.isEmpty() || !stack2.isEmpty()){
int levelNumber = !stack1.isEmpty()?stack1.size():stack2.size();
for(int i = 0;i < levelNumber;i++){
if((currentLevel & 1) == 1){
p = stack1.pop();
System.out.print(p.data + " ");
if(p.right != null){
stack2.push(p.right);
}
if(p.left != null){
stack2.push(p.left);
}
if(stack1.empty()){
currentLevel++;
}
}else {
p = stack2.pop();
System.out.print(p.data + " ");
if(p.left != null){
stack1.push(p.left);
}
if(p.right != null){
stack1.push(p.right);
}
if(stack2.empty()){
currentLevel++;
}
}
}
System.out.println();
}
}
近期评论