Home > Backend Development > C#.Net Tutorial > How to perform in-order traversal of a binary tree in C language?

How to perform in-order traversal of a binary tree in C language?

coldplay.xixi
Release: 2020-07-15 11:26:03
Original
3813 people have browsed it

The method of in-order traversal of a binary tree in C language: first traverse the left subtree, and continue to access the leftmost node with the help of recursion; then visit the root node; finally traverse the right subtree, and continue to access with the help of recursion Just go to the rightmost node.

How to perform in-order traversal of a binary tree in C language?

The method of in-order traversal of a binary tree in C language:

The rule of in-order traversal is: left subtree ---> Root node---> Right subtree. So the order in which we visit nodes needs to change.

  • We wait until the recursion is a round-trip process, for a node that has exactly two child nodes (no child nodes). You only need to visit the left node once, visit the root, and visit the right node. That’s it.

  • And if there are nodes on both sides. Each node must satisfy the rules of in-order traversal. We visit the left node first from the root. When it reaches the left node, the left node becomes a subtree again, which must also meet the requirements of in-order traversal. So we need to access the left node of the left node first (if it exists). So if you think so, you understand the rules. But it's too complicated. Then we use recursion. Because its sub-problems are the same as the problem of the root node, but the scope is reduced. So we use recursive thinking to solve it.

  • Then the recursive logic is: considering special circumstances (direct access if special), do not recurse, otherwise recursively access the left subtree (let the left subtree execute the same function, stop recursion if special) Output, if not special, keep looking until the leftmost node.)——>Output the node——>Recursively access the right subtree.

public void zhongxu(node t)// 中序遍历 中序遍历:左子树---> 根结点 ---> 右子树
{
if (t != null) {
zhongxu(t.left);
System.out.print(t.value + " ");// 访问完左节点访问当前节点
zhongxu(t.right);
}
}
Copy after login

Related learning Recommended: C video tutorial

The above is the detailed content of How to perform in-order traversal of a binary tree in C language?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template