如何在二叉搜索树中实现有序遍历?

本文详细介绍了如何在二叉搜索树中实现有序遍历,包括递归算法的实现过程。有序遍历首先访问左子树,然后访问根节点,最后访问右子树。这种深度优先算法在二叉搜索树中会按排序顺序打印节点。文章还提供了Java代码示例,以及进一步学习数据结构和算法的资源。
摘要由CSDN通过智能技术生成

disclosure: This post includes affiliate links; I may receive compensation if you purchase products or services from the different links provided in this article.
binary search tree inorder traversal in Java
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).

Top 10 Online Courses to learn Data Structure and Algorithms in Java

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遍历遍历二叉树的确切步骤:

  1. 访问左节点根的打印值 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.

inorder traversal in java using recursion

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.

from: https://dev.to//javinpaul/how-to-implement-inorder-traversal-in-a-binary-search-tree-1787

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值