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.
例如,在此问题中,基本情况是您到达叶节点并且没有更多要探索的节点,此时递归开始逐渐减弱。 以下是使用InOrder遍历遍历二叉树的确切步骤:
- 访问左节点根的打印值 visit right node\and here is the sample code to implement this algorithm using recursion in Java:
private void inOrder(TreeNode node) {
if (node == null) {
return;
}
inOrder(node.left);
System.out.printf("%s ", node.data);
inOrder(node.right);
}
Similar to preOrder() method in the last example, there is another inOrder() method which exposes inorder traversal to the public and calls this private method which actually performs the InOrder traversal.
这是编写需要输入的递归方法的标准方法,它使客户端可以更轻松地调用该方法。
public void inOrder() {
inOrder(root);
}
您可以看到我们从root开始,然后用node.left递归调用inOrder()方法,这意味着我们将在左子树上向下移动,直到达到node == null为止,这意味着最后一个节点是叶节点。
此时,为了() method will return and execute the next line, which prints the node.data. After that its again recursive 为了() call with node.right, which will initiate the same process again.
You can also check out Data Structure and Algorithms Part 1 and 2 courses on Pluralsight to learn more about algorithms and how to design your own algorithms.
Btw, you would need a Pluralsight membership to access this course, which costs around $29 monthly or $299 annually (14% saving). I have one and I also suggest all developers have that plan because Pluralsight is like NetFlix for Software developers.
它拥有有关所有最新主题的5000多种优质课程。 由于我们的程序员每天都必须学习新事物,因此299美元的投资也不错。
Btw, it also offers a 10-day free trial without any obligation which allows you to watch 200 hours of content. You can watch these courses for free by signing for that 10-day free trial.
InOrder traversal of a Binary tree in Java
这是我们Java中有序遍历算法的完整解决方案。 该程序使用递归算法通过InOrder遍历打印二叉树所有节点的值。
As I have told you before, during in-order traversal value of left subtree is printed first, followed by root and right subtree. If you are interested in the iterative algorithm, you can further check this tutorial of implementing in order traversal without recursion.
import java.util.Stack;
/*
* Java Program to traverse a binary tree
* using inorder traversal without recursion.
* In InOrder traversal first left node is visited, followed by root
* and right node.
*
* input:
* 40
* /\
* 20 50
* / \\
* 10 30 60
* / /\
* 5 67 78
*
* output: 5 10 20 30 40 50 60 67 78
*/
public class Main {
public static void main(String[] args) throws Exception {
// construct the binary tree given in question
BinaryTree bt = BinaryTree.create();
// traversing binary tree using InOrder traversal using recursion
System.out
.println("printing nodes of binary tree on InOrder using recursion");
bt.inOrder();
}
}
class BinaryTree {
static class TreeNode {
String data;
TreeNode left, right;
TreeNode(String value) {
this.data = value;
left = right = null;
}
}
// root of binary tree
TreeNode root;
/**
* traverse the binary tree on InOrder traversal algorithm
*/
public void inOrder() {
inOrder(root);
}
private void inOrder(TreeNode node) {
if (node == null) {
return;
}
inOrder(node.left);
System.out.printf("%s ", node.data);
inOrder(node.right);
}
/**
* Java method to create binary tree with test data
*
* @return a sample binary tree for testing
*/
public static BinaryTree create() {
BinaryTree tree = new BinaryTree();
TreeNode root = new TreeNode("40");
tree.root = root;
tree.root.left = new TreeNode("20");
tree.root.left.left = new TreeNode("10");
tree.root.left.left.left = new TreeNode("5");
tree.root.left.right = new TreeNode("30");
tree.root.right = new TreeNode("50");
tree.root.right.right = new TreeNode("60");
tree.root.left.right.left = new TreeNode("67");
tree.root.left.right.right = new TreeNode("78");
return tree;
}
}
输出量 使用递归在InOrder上打印二叉树的节点 5 10 20 30 67 78 40 50 60
就是这样如何使用递归在Java中实现二叉树的inOrder遍历。 您可以看到该代码与preOrder遍历非常相似,唯一不同的是我们递归调用该方法的顺序。 在这种情况下,我们首先调用inOrder(node.left),然后打印该节点的值。
值得记住的是,顺序遍历是一种深度优先算法,如果给定的二叉树是二叉搜索树,则按排序顺序打印树节点。
在本文的下一部分中,我将共享inOrder遍历而无需递归,同时,您可以尝试练习以下数据结构和二叉树问题。
Further Learning
Data Structures and Algorithms: Deep Dive Using Java
Algorithms and Data Structures - Part 1 and 2
Data Structures in Java 9 by Heinz Kabutz
Cracking the Coding Interview - 189 Questions and Solutions
Grokking the Coding Interview: Patterns for Coding Questions
100+ Data Structure and Algorithms Questions for Programmers
75+ Programming and Coding Interview Questions
其他数据结构和算法教程对于Java程序员
- 10 Algorithm books Every Programmer Should Read (list)
- How to implement Quicksort algorithm in Java? (solution)
- 5 Books to learn data structure and algorithms in Java? (books)
- How to implement a binary search algorithm in Java? (solution)
- How to find all pairs on integer array whose sum is equal to given a number? (solution)
- How to reverse an array in place in Java? (solution)
- How to reverse a linked list in Java without recursion? (solution)
- How to implement Insertion sort in Java? (solution)
- How to find the missing number in an array of 1 to 100? (solution)
- How to find the length of a singly linked list in Java? (solution)
- 15 frequently asked data structure and algorithm Interview Questions (list)
如果您有任何改进此算法的建议,请随时提出建议。 采访者喜欢那些提出自己的算法或对流行算法有所了解的人。
P.S. - If you don't mind learning from free resources then you can also take a look at my list of free data structure and algorithm courses for Java developers.