Four kinds of traversal of binary tree

Reprinted from: https://www.cnblogs.com/fly-me/p/wei-ti-jiaoer-cha-shu-de-si-zhong-bian-li-fang-fa.html

  Traversing a binary tree refers to starting from the root node and visiting all the nodes in the binary tree in a certain order , so that each node is visited sequentially and only once .

prologue middle Left right
Intermediate sequence Left middle right
post-order Left right middle
st=>start: 开始
e=>end: 结束
op=>operation: 根结点
op2=>operation: 左子树

io=>inputoutput: 右子树
cond=>condition: 二叉树是否为空?

st->cond
cond(yes)->e
cond(no)->e
op->op2->io->e

  • preorder traversal

If the tree is empty, the no-op returns. Otherwise, visit the root node first, then traverse the left subtree in preorder, and then traverse the right subtree in preorder. ( W ) type (middle left and right)

  • Inorder traversal

If the tree is empty, the no-op returns. Otherwise, starting from the root node (note that the root node is not visited first), the left subtree of the root node is traversed in order, then the root node is visited, and finally the right subtree of the root node is traversed in order. ( M ) type, (left middle right)

  • subsequent traversal

If the tree is empty, the no-op returns. Otherwise, the left and right subtrees are traversed from left to right, followed by the leaves and then the nodes, and finally the root node is visited. (left and right center) counterclockwise (left and right center)

  • level-order traversal

If the tree is empty, the no-op returns. Otherwise, the access starts from the first layer of the tree, that is, the root node, and traverses layer by layer from top to bottom. In the same layer, the nodes are accessed one by one in the order from left to right.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324775038&siteId=291194637