Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 869|回复: 0

二叉树的递归及非递归遍历 java实例

[复制链接]

该用户从未签到

发表于 2011-9-19 15:52:12 | 显示全部楼层 |阅读模式
着重介绍了非递归算法,特别是非递归后续遍历

package edu.cumt.jnotnull;
import java.util.Stack;
public class BinaryTree {
    protected Node root;
    public BinaryTree(Node root) {
        this.root = root;
    }
    public Node getRoot() {
        return root;
    }
    /** 构造树 */
    public static Node init() {
        Node a = new Node('A');
        Node b = new Node('B', null, a);
        Node c = new Node('C');
        Node d = new Node('D', b, c);
        Node e = new Node('E');
        Node f = new Node('F', e, null);
        Node g = new Node('G', null, f);
        Node h = new Node('H', d, g);
        return h;// root
    }
    /** 访问节点 */
    public static void visit(Node p) {
        System.out.print(p.getKey() + " ");
    }
    /** 递归实现前序遍历 */
    protected static void preorder(Node p) {
        if (p != null) {
            visit(p);
            preorder(p.getLeft());
            preorder(p.getRight());
        }
    }
    /** 递归实现中序遍历 */
    protected static void inorder(Node p) {
        if (p != null) {
            inorder(p.getLeft());
            visit(p);
            inorder(p.getRight());
        }
    }
    /** 递归实现后序遍历 */
    protected static void postorder(Node p) {
        if (p != null) {
            postorder(p.getLeft());
            postorder(p.getRight());
            visit(p);
        }
    }
    /** 非递归实现前序遍历 */
    protected static void iterativePreorder(Node p) {
        Stack<Node> stack = new Stack<Node>();
        if (p != null) {
            stack.push(p);
            while (!stack.empty()) {
                p = stack.pop();
                visit(p);
                if (p.getRight() != null)
                    stack.push(p.getRight());
                if (p.getLeft() != null)
                    stack.push(p.getLeft());
            }
        }
    }
    /** 非递归实现前序遍历2 */
    protected static void iterativePreorder2(Node p) {
        Stack<Node> stack = new Stack<Node>();
        Node node = p;
        while (node != null || stack.size() > 0) {
            while (node != null) {//压入所有的左节点,压入前访问它
                visit(node);
                stack.push(node);
                node = node.getLeft();
            }
            if (stack.size() > 0) {//
                node = stack.pop();
                node = node.getRight();
            }
        }
    }
    /** 非递归实现后序遍历 */
    protected static void iterativePostorder(Node p) {
        Node q = p;
        Stack<Node> stack = new Stack<Node>();
        while (p != null) {
            // 左子树入栈
            for (; p.getLeft() != null; p = p.getLeft())
                stack.push(p);
            // 当前节点无右子或右子已经输出
            while (p != null && (p.getRight() == null || p.getRight() == q)) {
                visit(p);
                q = p;// 记录上一个已输出节点
                if (stack.empty())
                    return;
                p = stack.pop();
            }
            // 处理右子
            stack.push(p);
            p = p.getRight();
        }
    }
    /** 非递归实现后序遍历 双栈法 */
    protected static void iterativePostorder2(Node p) {
        Stack<Node> lstack = new Stack<Node>();
        Stack<Node> rstack = new Stack<Node>();
        Node node = p, right;
        do {
            while (node != null) {
                right = node.getRight();
                lstack.push(node);
                rstack.push(right);
                node = node.getLeft();
            }
            node = lstack.pop();
            right = rstack.pop();
            if (right == null) {
                visit(node);
            } else {
                lstack.push(node);
                rstack.push(null);
            }
            node = right;
        } while (lstack.size() > 0 || rstack.size() > 0);
    }
    /** 非递归实现后序遍历 单栈法*/
    protected static void iterativePostorder3(Node p) {
        Stack<Node> stack = new Stack<Node>();
        Node node = p, prev = p;
        while (node != null || stack.size() > 0) {
            while (node != null) {
                stack.push(node);
                node = node.getLeft();
            }
            if (stack.size() > 0) {
                Node temp = stack.peek().getRight();
                if (temp == null || temp == prev) {
                    node = stack.pop();
                    visit(node);
                    prev = node;
                    node = null;
                } else {
                    node = temp;
                }
            }
        }
    }
    /** 非递归实现后序遍历4 双栈法*/
    protected static void iterativePostorder4(Node p) {
        Stack<Node> stack = new Stack<Node>();
        Stack<Node> temp = new Stack<Node>();
        Node node = p;
        while (node != null || stack.size() > 0) {
            while (node != null) {
                temp.push(node);
                stack.push(node);
                node = node.getRight();
            }
            if (stack.size() > 0) {
                node = stack.pop();
                node = node.getLeft();
            }
        }
        while (temp.size() > 0) {
            node = temp.pop();
            visit(node);
        }
    }
    /** 非递归实现中序遍历 */
    protected static void iterativeInorder(Node p) {
        Stack<Node> stack = new Stack<Node>();
        while (p != null) {
            while (p != null) {
                if (p.getRight() != null)
                    stack.push(p.getRight());// 当前节点右子入栈
                stack.push(p);// 当前节点入栈
                p = p.getLeft();
            }
            p = stack.pop();
            while (!stack.empty() && p.getRight() == null) {
                visit(p);
                p = stack.pop();
            }
            visit(p);
            if (!stack.empty())
                p = stack.pop();
            else
                p = null;
        }
    }
    /** 非递归实现中序遍历2 */
    protected static void iterativeInorder2(Node p) {
        Stack<Node> stack = new Stack<Node>();
        Node node = p;
        while (node != null || stack.size() > 0) {
            while (node != null) {
                stack.push(node);
                node = node.getLeft();
            }
            if (stack.size() > 0) {
                node = stack.pop();
                visit(node);
                node = node.getRight();
            }
        }
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree(init());
        System.out.print(" Pre-Order:");
        preorder(tree.getRoot());
        System.out.println();
        System.out.print("  In-Order:");
        inorder(tree.getRoot());
        System.out.println();
        System.out.print(&quotost-Order:");
        postorder(tree.getRoot());
        System.out.println();
        System.out.print(" Pre-Order:");
        iterativePreorder(tree.getRoot());
        System.out.println();
        System.out.print("Pre-Order2:");
        iterativePreorder2(tree.getRoot());
        System.out.println();
        System.out.print("  In-Order:");
        iterativeInorder(tree.getRoot());
        System.out.println();
        System.out.print(" In-Order2:");
        iterativeInorder2(tree.getRoot());
        System.out.println();
        System.out.print(" Post-Order:");
        iterativePostorder(tree.getRoot());
        System.out.println();
        System.out.print("Post-Order2:");
        iterativePostorder2(tree.getRoot());
        System.out.println();
        System.out.print("Post-Order3:");
        iterativePostorder3(tree.getRoot());
        System.out.println();
        System.out.print("Post-Order4:");
        iterativePostorder4(tree.getRoot());
        System.out.println();
    }
}
                        
二叉树节点类:

package edu.cumt.jnotnull;
public class Node {
    private char key;
    private Node left, right;
    public Node(char key) {
        this(key, null, null);
    }
    public Node(char key, Node left, Node right) {
        this.key = key;
        this.left = left;
        this.right = right;
    }
    public char getKey() {
        return key;
    }
    public void setKey(char key) {
        this.key = key;
    }
    public Node getLeft() {
        return left;
    }
    public void setLeft(Node left) {
        this.left = left;
    }
    public Node getRight() {
        return right;
    }
    public void setRight(Node right) {
        this.right = right;
    }
}
部分实现参照了网络资料
回复

使用道具 举报

该用户从未签到

发表于 2011-9-20 18:58:52 | 显示全部楼层
哇,好实例额。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

GMT+8, 2024-6-17 12:27 , Processed in 0.408624 second(s), 47 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表