Java中用递归和迭代实现二叉树的中序( InOrder )遍历


与数组和链表不同,二叉树有几种遍历方式。遍历算法大致分为深度优先和广度优先遍历算法,这取决于算法实际如何工作。顾名思义,深度优先在访问同级别兄弟之前先向二叉树纵深访问,而广度优先是先访问同一级别中的所有节点然后再进入下一级别,因此它也被称为级别顺序遍历。 PreOrder和InOrder树遍历算法都是深度优先的,预序和中序算法之间的唯一区别是访问二叉树的根,左节点和右节点的顺序。

InOrder遍历算法首先访问左节点,然后是root节点,最后是右节点。这与首先​​访问根的预序遍历不同。InOrder遍历的一个重要特性是,如果给定的二叉树是二叉搜索树,它将按排序顺序打印节点。

请记住,如果左子树中的所有节点都低于root并且右子树中的所有节点都大于root,则二叉树称为二叉搜索树。

在示例中,使用二叉搜索树来演示InOrder树遍历以排序顺序打印二叉树的节点,并分享了这个问题的递归和迭代解决方案。从面试的角度来看,这非常重要。即使递归解决方案更容易,占用更少的代码行,并且更具可读性,您也应该知道如何在没有Java递归的情况下遍历二叉树,以便在编程面试中做得更好。

Java中InOrder遍历二叉树 - 递归
由于二叉树是递归数据结构,因此递归是解决基于树的问题的最佳方法。以下是二叉树InOrder遍历的步骤:

1)访问左节点
2)访问root
3)访问右节点

要实现此算法,您可以使用InOrder遍历编写一个方法来遍历二叉树的所有节点,方法如下:

在inOrder(TreeNode节点)中编写方法
检查node == null,如果是,则返回,这是我们的基本情况。
调用inOrder(node.left)以递归方式访问左子树
打印节点的值
调用inOrder(node.right)以递归方式遍历右子树。

这将按照InOrder遍历打印二叉树的所有节点。如果二叉树是二叉搜索树,则树的所有节点将按排序顺序打印。这是一种在Java中实现InOrder算法的方法:

private void inOrder(TreeNode node) {
    if (node == null) {
      return;
    }

    inOrder(node.left);
    System.out.printf("%s ", node.data);
    inOrder(node.right);
  }

该方法是私有方法,因为它是通过另一个公共方法inorder()公开的,后者不需要来自客户端的参数。这是一个facade模式的例子,它使客户端的方法更简单。递归算法很容易理解,深入到左子树,直到找到叶节点。一旦找到,递归堆栈就开始展开,打印节点数据并开始探索右子树。

Java中InOrder遍历二叉树 - 迭代
您可以使用堆栈将递归的顺序算法转换为迭代的顺序算法。。 没有递归的解决方案虽然不容易阅读,但也不是很难理解。 我们从根和进程开始,直到当前节点或Stack不为空。 我们开始从左子树推节点,直到到达叶节点。 此时,我们pop()最后一个元素,打印它的值,并通过指定current=current.right开始探索右子树。这将一直持续到堆栈变空为止,此时,二叉树的所有元素都被访问,树遍历完成。

 

  4
   / \
  2   5
 / \   \
1   3   6 

public void inOrderWithoutRecursion() {
    Stack nodes = new Stack<>();
    TreeNode current = root;

    while (!nodes.isEmpty() || current != null) {

      if (current != null) {
        nodes.push(current);
        current = current.left;
      } else {
        TreeNode node = nodes.pop();
        System.out.printf("%s ", node.data);
        current = node.right;
      }

    }
  }

Output
1 2 3 4 5 6 

因为我们的二叉树是一个二叉搜索树,所以可以看到它们是按排序顺序打印的。

Java中使用InOrder算法遍历二叉树
这是我们在Java中使用InOrder算法遍历二叉树的完整程序。类似于我们之前看到的preOrder示例,唯一的区别是root的访问顺序不是首先而是其次。 递归算法很简单,但迭代算法有点难以理解。您必须记住,堆栈是一个后进先出的数据结构,您先推的节点将最后弹出。因为您需要按左--右的顺序访问节点,所以您必须先推左树的节点,直到到达叶节点。然后打印该值并开始访问右子树。
我们使用了相同的BinaryTree和TreeNode类,在早期的基于树的问题(例如计算叶节点)中,它用于表示二叉树。二叉树是常规二叉树,TreeNode表示二叉树中的节点。

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:
 *     4
 *    / \
 *   2   5
 *  / \   \
 * 1   3   6
 * 
 * output: 1 2 3 4 5 6 
 */


public class InOrderTraversal {

  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 a binary tree on InOrder using recursion");

    bt.inOrder();

    System.out.println();
// insert new line

   
// traversing binary tree on InOrder traversal without recursion
    System.out
        .println(
"printing nodes of binary tree on InOrder using iteration");
    bt.inOrderWithoutRecursion();
  }

}

class BinaryTree {
  static class TreeNode {
    String data;
    TreeNode left, right;

    TreeNode(String value) {
      this.data = value;
      left = right = null;
    }

    boolean isLeaf() {
      return left == null ? right == null : false;
    }

  }

 
// 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);
  }

  public void inOrderWithoutRecursion() {
    Stack nodes = new Stack<>();
    TreeNode current = root;

    while (!nodes.isEmpty() || current != null) {

      if (current != null) {
        nodes.push(current);
        current = current.left;
      } else {
        TreeNode node = nodes.pop();
        System.out.printf(
"%s ", node.data);
        current = 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(
"4");
    tree.root = root;
    tree.root.left = new TreeNode(
"2");
    tree.root.left.left = new TreeNode(
"1");

    tree.root.left.right = new TreeNode(
"3");
    tree.root.right = new TreeNode(
"5");
    tree.root.right.right = new TreeNode(
"6");

    return tree;
  }

}

Output
printing nodes of a binary tree on InOrder using recursion
1 2 3 4 5 6 
printing nodes of a binary tree on InOrder using iteration
1 2 3 4 5 6 

这就是如何使用InOrder遍历算法访问二叉树的所有节点。 正如我之前所说,InOrder是一种深度优先遍历算法,在访问root之前首先探索左子树,最后探索右子树,因此它也被称为LNR(左节点右)算法。 inorder遍历还有一个独特的属性,如果给定的二叉树是二叉搜索树,它会按排序顺序打印节点。 因此,如果必须按BST的排序顺序打印所有节点,则可以使用此算法。