BinaryTree

import java.io.IOException;
import java.util.Stack;
 
public class BinaryTree {
 
    private char root;
    private BinaryTree left;
    private BinaryTree right;
    private int height;
 
    /*
     * Internal a binaryTree by one element
     * 
     * @param element the required
     */
    BinaryTree(char element) {
        this(element, null, null);
    }
 
    /*
     * Internal a binaryTree by three element
     * 
     * @param element the root element
     * 
     * @param lt the left subtree
     * 
     * @param rt the right subtree
     */
    BinaryTree(char element, BinaryTree lt, BinaryTree rt) {
        root = element;
        left = lt;
        right = rt;
    }
 
    /*
     * Internal the method to insert into a binaryTree
     * 
     * @param element the insert element
     * 
     * @param bt the tree needed to insert
     */
    private BinaryTree insert(char element, BinaryTree bt) {
        if (bt == null)
            return new BinaryTree(element);
 
        int compareResult = element - bt.root;
        if (compareResult > 0) {
            bt.right = insert(element, bt.right);
        }
        if (compareResult < 0) {
            bt.left = insert(element, bt.left);
        } else
            ;
        bt.height = Math.max(height(bt.left), height(bt.right)) + 1;
        return bt;
    }
 
    /*
     * Return the height of node t, or -1, if null.
     */
 
    private int height(BinaryTree t) {
        return t == null ? -1 : t.height;
    }
 
    private void PreTravel(BinaryTree k1)// travel a tree by pre-order
    {
        if (k1 == null)
            return;
        else {
            System.out.print(k1.root);
            PreTravel(k1.left);
            PreTravel(k1.right);
        }
    }
 
    private void MidTravel(BinaryTree k1)// travel a tree by mid-order
    {
        if (k1 == null)
            return;
        else {
            MidTravel(k1.left);
            System.out.print(k1.root);
            MidTravel(k1.right);
        }
    }
 
    private void SufTravel(BinaryTree k1)// travel a tree by suf-order
    {
        if (k1 == null)
            return;
        else {
            SufTravel(k1.left);
            SufTravel(k1.right);
            System.out.print(k1.root);
        }
    }
 
    /*
     * Internal method to travel a tree without recursion
     * 
     * @param k1 the tree to be traveled
     */
    private void PreSTravel(BinaryTree k1) {
        Stack<BinaryTree> s = new Stack<BinaryTree>();
        if (k1 == null)
            return;
        else {
            System.out.print(k1.root);
            s.push(k1.right);
            s.push(k1.left);
        }
        while (!s.empty()) {
            BinaryTree bt = s.pop();
            if (bt != null) {
                System.out.print(bt.root);
                s.push(bt.right);
                s.push(bt.left);
            }
        }
    }
 
    /*
     * Internal method to travel a tree by cursion in mid
     * 
     * @param k1 the tree to be traveled
     */
    private void MidSTravel(BinaryTree k1) {
        Stack<BinaryTree> s = new Stack<BinaryTree>();
        BinaryTree bt = k1;
        while (bt != null || !s.empty()) {
            while (bt != null) {//先把左子树都压入栈
                s.push(bt);
                bt = bt.left;
            }
            if (!s.empty()) {
                bt = s.pop();//弹出栈顶
                System.out.print(bt.root);
                bt = bt.right;
            }
        }
    }
 
    /*
     * Internal method to travel a tree without crusion in suf
     * 
     * @param k1 the tree to be traveled
     */
    private void SufSTravel(BinaryTree k1) {//后序遍历算法,先遍历当前节点的左孩子,右孩子,最后访问当前节点
        Stack<BinaryTree> s = new Stack<BinaryTree>();
        BinaryTree cur;
        BinaryTree pre = null;
        s.push(k1);
        while (!s.empty()) {
            cur = s.peek();
            if ((cur.left == null && cur.right == null) //当前节点为叶子节点或者孩子节点都已经被访问过了
                    || (pre != null && (pre == cur.left || pre == cur.right))) {
                System.out.print(cur.root); //访问当前节点
                s.pop();
                pre = cur; //用来判断访问和下一次访问是否相同
            } else {//如果不是,则将左孩子压入栈,去看左孩子是否有孩子或者是否遍历过
                if (cur.right != null)
                    s.push(cur.right);
                if (cur.left != null)
                    s.push(cur.left);
            }
        }
    }
 
    /*
     * Internal the method to describe a tree
     * 
     * @param bt the tree needed to be describe
     */
    private void display(BinaryTree bt) {
        if (bt != null) {
            System.out.print(bt.root);
            if (bt.left != null) {
                System.out.print("(");
                display(bt.left);
            }
            if (bt.right != null) {
                System.out.print(",");
                display(bt.right);
                System.out.print(")");
            }
        }
    }
 
    public static void main(String[] args) {
        String test = "749358";
        // TODO Auto-generated method stub
        char ch = 0;
        try {
            ch = (char) System.in.read();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        BinaryTree bt = new BinaryTree(ch);
        try {
            ch = (char) System.in.read();
            while (ch != ‘#‘) {
                bt.insert(ch, bt);
                ch = (char) System.in.read();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        System.out.println(bt.height);
        System.out.print("树的结构为: ");
        bt.display(bt);
        System.out.println();
        System.out.print("前序遍历<递归>: ");
        bt.PreTravel(bt);
        System.out.println();
        System.out.print("前序遍历<栈>: ");
        bt.PreSTravel(bt);
        System.out.println();
        System.out.print("中序遍历<递归>: ");
        bt.MidTravel(bt);
        System.out.println();
        System.out.print("中序遍历<栈>: ");
        bt.MidSTravel(bt);
        System.out.println();
        System.out.print("后序遍历<递归>: ");
        bt.SufTravel(bt);
        System.out.println();
        System.out.print("后序遍历<栈>: ");
        bt.SufSTravel(bt);
    }
 
}
时间: 2024-07-30 10:21:01

BinaryTree的相关文章

java数据结构与算法之树基本概念及二叉树(BinaryTree)的设计与实现

[版权申明]未经博主同意,不允许转载!(请尊重原创,博主保留追究权) http://blog.csdn.net/javazejian/article/details/53727333 出自[zejian的博客] 关联文章: java数据结构与算法之顺序表与链表设计与实现分析 java数据结构与算法之双链表设计与实现 java数据结构与算法之改良顺序表与双链表类似ArrayList和LinkedList(带Iterator迭代器与fast-fail机制) java数据结构与算法之栈(Stack)设

数据结构与算法---线索化二叉树(Threaded BinaryTree)

先看一个问题 将数列 {1, 3, 6, 8, 10, 14  } 构建成一颗二叉树 问题分析: 当我们对上面的二叉树进行中序遍历时,数列为 {8, 3, 10, 1, 6, 14 } 但是 6, 8, 10, 14 这几个节点的 左右指针,并没有完全的利用上. 如果我们希望充分的利用 各个节点的左右指针, 让各个节点可以指向自己的前后节点,怎么办? 解决方案-线索二叉树 线索二叉树基本介绍 1.n个结点的二叉链表中含有n+1  [公式 2n-(n-1)=n+1] 个空指针域.利用二叉链表中的空

binaryTree.js

function Node(data, left, right) { this.data = data; this.left = left; this.right = right; this.show = show; } function show() { return this.data; } function BST() { this.root = null; this.insert = insert; this.inOrder = inOrder; } function insert(da

BinaryTree II

初级木遁忍术‘树界降临’掌握完毕. 一心追逐无上忍术的我,准备学习进阶的忍术 木遁-森罗万象! ------------------ switch ------------------- 中级篇      综述二叉查找树的类框架及各种眼花缭乱的DFS递归. 二叉树类的逻辑思维要求较高,细节要求较严谨. 此篇代码大部摘自著作 <数据结构与算法分析 C++描述>.     此类通过公有函数对私有函数的调用及私有函数的递归运用,巧妙实现了二叉树的构建,查找,删除等功能. 以下是代码框架.后续给出部分

BinaryTree I

七月流火季节,小生独上数据结构算法山修炼内功,以防日后遇武林高手无法抵御 ... ... 今日Mark Allen Weiss师父传授的是 木遁-‘树界’降临 ... ... ------------------  Switch -------------------- 初级篇 简介下如何运用栈创建一个简单的二叉树.以建立表达式树为例. 程序逻辑比较清晰,对于一个后缀表达式,遇数字开辟树结点,入栈.遇操作符,弹出栈顶两元素,作为开辟树结点的参数,后入栈. 小小的难点在于DFS遍历树的递归运用.

[BinaryTree] 二叉树常考知识点

1.二叉树第i层至多有2^(i-1)个结点(i>=1). 2.深度为k的二叉树上,至多含2^k-1个结点(k>=1) 3.n0 = n2 + 1(度) 4.满二叉树:深度为k且含有2^k-1个结点的树. 5.完全二叉树:除最后一层外,每一层上的节点数均达到最大值:在最后一层上只缺少右边的若干结点. (树中所含n个结点和满二叉树中编号为1至n的结点一一对应). 6.具有n个结点的完全二叉树的深度为[log2n] + 1. 7.二叉树的链式存储表示:二叉链表.三叉链表(增加双亲指针域).双亲链表.

Add Digits, Maximum Depth of BinaryTree, Search for a Range, Single Number,Find the Difference

最近做的题记录下. 258. Add Digits Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. For example: Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 1 int addDi

二叉树的镜像

什么是二叉树的镜像呢? 我们可以自己画一颗二叉树.然后根据照镜子画出它的镜像. 如: 我们不能一次得到二叉树的镜像,要想得到一颗二叉树的镜像,有以下几个步骤: (1)先交换根的左子树和右子树 (2)交换6的左子树和右子树                      (3)交换10的左子树和右子树 得出以上规律后,就可以写代码喽: class BinaryTreeNode { public: BinaryTreeNode(const T& data) :_data(data) ,_left(NULL

二叉树

介绍二叉树之前呢,我们先来说说树? 树呢,顾名思义,长得像一棵树,不过通常我们画成一颗倒过来的树,根在上,叶在下.还是看图吧. 既然说到树了,那就说说树的一些基本概念吧.用图说明. 树的存储结构: 下面呢,就来介绍树的特殊例子---二叉树 所谓二叉树呢,就是父节点最多有两个孩子. 二叉树的存储结构: (1)数组存储 数组存储即用一块连续内存来存储二叉树. 若二叉树为满二叉树或者完全二叉树时,用数组存储非常有效,但是对于一般的二叉树来说,效果并不是很好.若要在二叉树中进行增删的话,可能要挪动大量的