Binary tree non-recursive preorder traversal (java)

Ideas

In the recursive method, you need to use a stack to record when you press the node so that you can return to the right subtree for traversal after completing the left subtree. In order to simulate the same operation, first process the current node. Before traversing the left subtree, The current node remains in the stack. When the left subtree is traversed, the element is popped out of the stack, and then the right subtree is found for traversal. Continue the process and the guidance is empty

void PreOrderNonRecursive(BinaryTreeNode root){
    
    
  if(root == null){
    
    
    return null;
  }
  LLStack s = new LLStack();
  while(true){
    
    
    while(root != null){
    
    
      System.out.println(root.getData());
      s.push(root);
      root = root.getLeft();
    }
    if(s.isEmpty()){
    
    
      break;
    }
    root = (BinaryTreeNode)s.pop();
    root = root.getRight();
  }
  return;
}

Guess you like

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