disclosure: This post includes affiliate links; I may receive compensation if you purchase products or services from the different links provided in this article.
The InOrder traversal is one of the three popular ways to traverse a binary tree data structure, the other two being the preOrder and postOrder. During the in-order traversal algorithm, the left subtree is explored first, followed by root, and finally nodes on the right subtree.
您从根开始遍历,然后转到左侧节点,然后再次转到左侧节点,直到到达叶节点。 此时,您将打印节点的值或将其标记为已访问并移至右侧子树。 继续相同的算法,直到访问了二叉树的所有节点。 InOrder遍历也称为左节点右要么从左到右 traversal要么LNR遍历算法。
Similar to the preOrder algorithm, it is also a depth-first algorithm because it explores the depth of a binary tree before exploring siblings. Since it is one of the fundamental binary tree algorithms it's quite popular in programming interviews.
这些遍历算法也是学习更高级的二叉树算法的基础,因此每个程序员都应该学习,理解和知道如何实现有序遍历和其他遍历算法。
The easiest way to implement the inOrder traversal algorithm in Java or any programming language is by using recursion. Since the binary tree is a recursive data structure, recursion is the natural choice for solving a tree-based problem. The inOrder() method in the BinaryTree class implements the logic to traverse a binary tree using recursion.
From Interview point of view, InOrder traversal is extremely important because it also prints nodes of a binary search tree in the sorted order but only if given tree is binary search tree. If you remember, in BST, the value of nodes in left subtree is lower than the root and values of nodes on right subtree is higher than root. The In order traversal literally means IN order i.e notes are printed in the order or sorted order.
Btw, even though these three algorithms (pre-order, in-order, and post-order) are popular binary tree traversal algorithms but they are not the only ones. You also have other breadth-first ways to traverse a binary tree e.g. level order traversal (See Data Structure and Algorithms: Deep Dive).
The recursive algorithm to implement InOrder traversal of a Binary tree
The recursive algorithm of inorder traversal is very simple. You just need to call the inOrder() method of BinaryTree class in the order you want to visit the tree. What is most important is to include base case, which is key to any recursive algorithm.
例如,在此问题中,基本情况是您到达叶节点并且没有更多要探索的节点,此时递归开始逐渐减弱。 以下