设为首页 加入收藏

TOP

Java实现二叉树的遍历(一)
2017-10-18 09:07:52 】 浏览:8411
Tags:Java 实现

Java实现二叉树的遍历


public class BinaryTreeNode {
    int value;
    BinaryTreeNode left;
    BinaryTreeNode right;
 
    // 前序遍历
    public static void preOrder(BinaryTreeNode tree) {
        if (tree == null)
            return;
        System.out.print(tree.value + " ");
        preOrder(tree.left);
        preOrder(tree.right);
    }
 
    /**
    * 二叉树前序遍历的循环实现方式
    * 
    * @param tree
    */
    public static void preOrderLoop(BinaryTreeNode tree) {
        if (tree == null)
            return;
        Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>();
        BinaryTreeNode node = tree;
 
        while (node != null || !stack.isEmpty()) {
            if (node != null) {
                stack.push(node);
                System.out.print(node.value + " ");
                node = node.left;
            } else {
                BinaryTreeNode item = stack.pop();
                node = item.right;
            }
        }
    }
 
    // 中序遍历
    public static void inOrder(BinaryTreeNode tree) {
        if (tree == null)
            return;
        inOrder(tree.left);
        System.out.print(tree.value + " ");
        inOrder(tree.right);
    }
 
    /**
    * 二叉树中序遍历的循环实现
    * 
    * @param tree
    */
    public static void inOrderLoop(BinaryTreeNode tree) {
        if (tree == null)
            return;
        Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>();
        BinaryTreeNode node = tree;
 
        while (node != null || !stack.empty()) {
            if (node != null) {
                stack.push(node);
                node = node.left;
            } else {
                BinaryTreeNode item = stack.pop();
                System.out.print(item.value + " ");
                node = item.right;
            }
        }
    }
 
    // 后序遍历
    public static void postOrder(BinaryTreeNode tree) {
        if (tree == null)
            return;
        postOrder(tree.left);
        postOrder(tree.right);
    &n

首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python 实现单例模式 下一篇C#实现二叉树的遍历

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目