Implement ZigZag Traversal of Binary Tree with Java

Design algorithm to traverse binary tree in ZigZag order

answer

Assuming that the two stacks are currentlevel and nextLevel, use a variable to track the order of the current level, pop the node from currentLevel, and output its value. When the current level is from left to right, follow the order of the left child first and then the right child. The order is pushed into the stack nextLevel. Because the stack is a last-in-first-out structure, the next stack output order is reversed. In addition, if the current layer is from right to left, it will be pushed into the stack according to the right child node first and then the left child node. In addition, at the end of each layer, the two stacks need to be exchanged

Code

void zigZagTraversal(BinaryTreeNode root){
    
    
  BinaryTreeNode temp;
  if(root == null)
   return;
  Stack currentLevel = new Stack();
  Stack nextLevel = new Stack();
  currentLevel.push(root);
  while(currentLevel.isNotEmpty()){
    
    
    temp = currentLevel.pop();
    if(temp != null){
    
    
      System.out.println(temp.getData());
      if(leftToRight){
    
    
        if(temp.getLeft() != null){
    
    
          nextLevel.push(temp.getLeft());
        }
        if(temp.getRight() != null){
    
    
          nextLevel.push(temp.getRight());
        }
      }
      else{
    
    
        if(temp.getRight() != null){
    
    
          nextLevel.push(temp.getRight());
        }
        if(temp.getLeft() != null){
    
    
          nextLevel.push(temp.getLeft());
        }
      }
    }
    if(currentLevel.isEmpty()){
    
    
      if(leftToRight){
    
    
        leftToRight = false;
      }else{
    
    
        leftToRight = true;
      }
      Stack tempLevel = new Stack();
      tempLevel = currentLevel;
      currentlevel = nextLevel;
      nextLevel = temp;
    }
  }

}

Guess you like

Origin blog.csdn.net/weixin_37632716/article/details/114849883