Tree)
A tree, as its name implies, looks like a tree, but we usually draw a fallen tree with its roots and leaves under it. If you don't say that much, you can see the following figure:
Of course, after the introduction of the tree, we have to introduce some concepts of the tree. I still try to use these concepts with graphs. Who will remember so many words?
During interviews, we often get a binary tree structure. Of course, binary trees are also a kind of tree, it has two sub-nodes except leaf nodes:
As a result, we can also launch the "Three Tree ":
Of course, there are also "Four Forks", "Five Forks", and "Six Forks "...... But it is too difficult to draw. There are too many nodes, and it is skipped.
Traverse a tree (traversal)
It is worth mentioning that it is a binary tree, because it is indeed quite special, the node has two Subtrees, the two Subtrees are divided between the left and right, upside down, is a different binary tree, therefore, the left and right cannot be reversed.
When talking about the "team" in the third article, we mentioned breadth-first traversal. In addition to breadth-first traversal, we also mentioned depth-first traversal ), depth-first traversal can be divided into preorder traversal, postorder traversal, and inorder traversal, explain these traversal types:
Okay, nowCodeStage: write code. I have read many textbooks on data structures. binary tree traversal is essential, and all I know is implemented using recursion. Now, I want you to skip recursion, implements sequential traversal of Binary Trees. What should I do? I will give you a tip: We used the team to traverse the breadth first. We used the * stack * to traverse the middle order *. Let's see if it can be written: