Java 二叉树遍历

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("Post-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();  

    }  

}

  

class DataNode{
    int data;
    DataNode leftChild = null;
    DataNode rightChild = null;
}

public class NodeTree {

    DataNode rootNode;
    DataNode tempNode;
    //int index_root;
    DataNode left_childDataNode;
    DataNode right_childDataNode;

    public DataNode initRootNode(int[] preArray){
        rootNode = new DataNode();
        rootNode.data = preArray[0];
        return rootNode;
    }

    public  void BuildTree(int[] preArray,int[] midArray,DataNode rootNode){
        int index_root = getIndex(midArray, rootNode.data);
        int lengthOfRightTree = preArray.length - index_root -1;

        int[] preArray_left;
        int[] preArray_right;
        int[] midArray_left;
        int[] midArray_right;

        if (index_root>0) {
            left_childDataNode = new DataNode();
            if (index_root==1) {
                left_childDataNode.data = midArray[0];
                rootNode.leftChild = left_childDataNode;
            }else {
                preArray_left = new int[index_root];
                midArray_left = new int[index_root];
                System.arraycopy(preArray, 1, preArray_left, 0, index_root);
                System.arraycopy(midArray, 0, midArray_left, 0, index_root);
                left_childDataNode.data = preArray_left[0];
                rootNode.leftChild = left_childDataNode;
                BuildTree(preArray_left, midArray_left, left_childDataNode);
            }
        }

        if (lengthOfRightTree>0) {
            right_childDataNode = new DataNode();
            if (lengthOfRightTree==1) {
                right_childDataNode.data = midArray[index_root+1];
                rootNode.rightChild = right_childDataNode;
                return;
            }else {
                preArray_right  = new int[lengthOfRightTree];
                midArray_right = new int[lengthOfRightTree];
                System.arraycopy(preArray, index_root+1, preArray_right, 0,lengthOfRightTree);
                System.arraycopy(midArray, index_root+1, midArray_right, 0, lengthOfRightTree);
                right_childDataNode.data = preArray_right[0];
                rootNode.rightChild = right_childDataNode;
                BuildTree(preArray_right, midArray_right,right_childDataNode);
            }
        }
    }

    public int getIndex(int[] array,int temp){
        int index = -1;
        for (int i = 0; i < array.length; i++) {
            if (array[i]==temp) {
                index = i;
                return index;
            }
        }
        return index;
    }
    //后序遍历
    public void postOrderTraverse(DataNode node){
        if (node==null) {
            return;
        }
        postOrderTraverse(node.leftChild);
        postOrderTraverse(node.rightChild);
        System.out.print(node.data);
    }
    //前序遍历
    public void preOrderTraverse(DataNode node){
        if (node==null) {
            return;
        }
        System.out.print(node.data);
        preOrderTraverse(node.leftChild);
        preOrderTraverse(node.rightChild);
    }
    //中序遍历
    public void inOrderTraverse(DataNode node){
        if (node==null) {
            return;
        }
        inOrderTraverse(node.leftChild);
        System.out.print(node.data);
        inOrderTraverse(node.rightChild);
    }

    public static void main(String args[]){
        int[] preArray = {1,2,3};
        int[] midArray = {1,2,3};
        NodeTree tree = new NodeTree();
        DataNode headNode = tree.initRootNode(preArray);
        tree.BuildTree(preArray, midArray, headNode);
        tree.postOrderTraverse(headNode);
    }

}

  

时间: 2024-10-12 20:04:39

Java 二叉树遍历的相关文章

Java 二叉树遍历右视图-LeetCode199

题目如下: 题目给出的例子不太好,容易让人误解成不断顺着右节点访问就好了,但是题目意思并不是这样. 换成通俗的意思:按层遍历二叉树,输出每层的最右端结点. 这就明白时一道二叉树层序遍历的问题,用一个队列来处理,但是问题是怎么来辨别每层的最右端结点,我思考了半天,最后想出的办法是利用一个标记位,例如上面的例子: q代表队列,f代表标记结点,right代表记录的最右端结点 q: 1 flag right:{} q: flag 2 3 遇到标记位所以移动标记位,并将队头弹出的数据存起来如下 q: 2

java实现二叉树遍历

package com.tree.demo; public class BinaryTree { int data; // 根节点数据   BinaryTree left; // 左子树 BinaryTree right; // 右子树 public BinaryTree(int data) // 实例化二叉树类 { this.data = data; left = null; right = null; } public void insert(BinaryTree root, int dat

Java递归方法遍历二叉树的代码

将内容过程中经常用的内容做个记录,如下内容内容是关于Java递归方法遍历二叉树的内容. package com.wzs; public class TestBinaryTree { public static void main(String[] args) { Node<String> g = new Node<String>("G", null, null); Node<String> e = new Node<String>(&qu

二叉树遍历-JAVA实现

二叉树遍历分为前序.中序.后序递归和非递归遍历.还有层序遍历. 1 //二叉树节点 2 public class BinaryTreeNode { 3 private int data; 4 private BinaryTreeNode left; 5 private BinaryTreeNode right; 6 7 public BinaryTreeNode() {} 8 9 public BinaryTreeNode(int data, BinaryTreeNode left, Binar

java数据结构之二叉树遍历的非递归实现

算法概述递归算法简洁明了.可读性好,但与非递归算法相比要消耗更多的时间和存储空间.为提高效率,我们可采用一种非递归的二叉树遍历算法.非递归的实现要借助栈来实现,因为堆栈的先进后出的结构和递归很相似.对于中序遍历来说,非递归的算法比递归算法的效率要高的多.其中序遍历算法的实现的过程如下:(1).初始化栈,根结点进栈:(2).若栈非空,则栈顶结点的左孩子结点相继进栈,直到null(到叶子结点时)退栈:访问栈顶结点(执行visit操作)并使栈顶结点的右孩子结点进栈成为栈顶结点.(3).重复执行(2),

算法之二叉树遍历

[代码示例] package com.wcs.java; import java.util.ArrayList; import java.util.List; public class BinaryTree { class TreeNode { public String data; //数据 public TreeNode leftNode; //左子树 public TreeNode rightNode; //右子树 public TreeNode(String data, TreeNode

java二叉树

网上有关于二叉数的java实现http://blog.csdn.net/skylinesky/article/details/6611442 多数案例都没有键值,有键值的也全是整型.我用java实现了一个可以任何对象为键的二叉数 package Tree; import java.io.IOException; public class Tree<I extends Comparable<I> ,V> { @SuppressWarnings("rawtypes"

Java数据结构 遍历 排序 查找 算法实现

1. 遍历算法(遍历二叉树6种方法) 1.1. 概述 遍历算法针对二叉树而言的,主要有先序.中序.后序三种遍历顺序,三种顺序又分别有递归和常规算法,二叉树遍历的主要思想是:遍历左子树,遍历右子树,访问根节点,由这三者的遍历顺序来确定是先序.中序还是后序.下面只要求掌握递归遍历算法,常规遍历算法见附录一. 1.2. 先序遍历算法 遍历顺序:访问根节点,遍历左子树,遍历右子树.代码如下: void preOrder(BinaryTreeNode bt) { if (bt == null)// 如果当

二叉树遍历(先序、中序、后序)

二叉树的遍历(递归与非递归) 遍历:traversal 递归:recursion 栈----------回溯----------递归 栈和回溯有关 本文讨论二叉树的常见遍历方式的代码(Java)实现,包括 前序(preorder).中序(inorder).后序(postorder).层序(level order), 进一步考虑递归和非递归的实现方式. 递归的实现方法相对简单,但由于递归的执行方式每次都会产生一个新的方法调用栈,如果递归层级较深,会造成较大的内存开销, 相比之下,非递归的方式则可以