java 来自http://www.java67.com/2016/08/binary-tree-inorder-traversal-in-java.html

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 来自http://www.java67.com/2016/08/binary-tree-inorder-traversal-in-java.html相关的知识,希望对你有一定的参考价值。

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.right.right.left = new TreeNode("67");
    tree.root.right.right.right = new TreeNode("78");

    return tree;
  }

}

Output
printing nodes of binary tree on InOrder using recursion
5 10 20 30 40 50 67 60 78

以上是关于java 来自http://www.java67.com/2016/08/binary-tree-inorder-traversal-in-java.html的主要内容,如果未能解决你的问题,请参考以下文章

Java Me 视频播放器使用 http 实现错误 - MediaException

操作无法完成。找不到 Java 运行时。有关安装 Java 的信息,请访问 http://www.java.com

java相关网址

适合JAVA新手学习的网站

shell67批量创建用户(来自文件)

开源项目网址收藏