简单二叉树

import java.util.Arrays;
import java.util.Random;
import java.util.Stack;

public class BinaryTreeNode<T extends Comparable<T>> implements Comparable<T> {
    public T data;
    public BinaryTreeNode<T> parent;
    public BinaryTreeNode<T> childL;
    public BinaryTreeNode<T> childR;

    public BinaryTreeNode() {
        this(null);
    }

    public BinaryTreeNode(T data) {
        this(data, null);
    }

    public BinaryTreeNode(T data, BinaryTreeNode<T> parent) {
        this(data, parent, null, null);
    }

    public BinaryTreeNode(T data, BinaryTreeNode<T> parent, BinaryTreeNode<T> childL, BinaryTreeNode<T> childR) {
        super();
        this.data = data;
        this.parent = parent;
        this.childL = childL;
        this.childR = childR;
    }

    @Override
    public int compareTo(T e) {
        if (data == e) {
            return 0;
        }
        if (data == null) {
            return -1;
        }
        if (e == null) {
            return 1;
        }
        return data.compareTo(e);
    }

    @Override
    public String toString() {
        return String.valueOf(data);
    }

    //获得当前树的跟节点
    public final BinaryTreeNode<T> getRoot() {
        if (parent == null) {
            return this;
        }
        BinaryTreeNode<T> root = parent;
        while (root.parent != null) {
            root = root.parent;
        }
        return root;
    }

    public final BinaryTreeNode<T> find(T target) {
        int i;
        BinaryTreeNode<T> node = this;
        while (true) {
            i = node.compareTo(target);
            if (i > 0) {
                if (node.childL != null) {
                    node = node.childL;
                } else {
                    return null;
                }
            } else if (i < 0) {
                if (node.childR != null) {
                    node = node.childR;
                } else {
                    return null;
                }
            } else {
                return node;
            }
        }
    }

    public final void add(T element) {
        if (element == null) {
            return;
        }
        if (this.data == null) {
            this.data = element;
            return;
        }
        int i;
        BinaryTreeNode<T> node = this;
        while (true) {
            i = node.compareTo(element);
            if (i > 0) {
                if (node.childL != null) {
                    node = node.childL;
                } else {
                    node.childL = new BinaryTreeNode<>(element, node);
                }
            } else if (i < 0) {
                if (node.childR != null) {
                    node = node.childR;
                } else {
                    node.childR = new BinaryTreeNode<>(element, node);
                }
            } else {
                return;
            }
        }
    }

    //删除当前节点
    public final void del() {
        BinaryTreeNode<T> replace;
        //如果具有左节点则取左边最大值进行替换
        if ((replace = this.childL) != null) {
            while (replace.childR != null) {
                replace = replace.childR;//循环找到左侧最大元素
            }
            //替补节点是删除节点的左节点
            if (this.childL == replace) {
                this.childL = replace.childL;
            } else {
                replace.parent.childR = replace.childL;
            }
            //移交替补可能存在的子节点
            if (replace.childL != null) {
                replace.childL.parent = replace.parent;
            }
        } else if ((replace = this.childR) != null) {
            //如果具有右节点则取右边最小值进行替换
            while (replace.childL != null) {
                replace = replace.childL;//循环找到右侧最大元素
            }
            if (this.childR == replace) {
                this.childR = replace.childR;
            } else {
                replace.parent.childL = replace.childR;
            }
            if (replace.childR != null) {
                replace.childR.parent = replace.parent;
            }
        }
        //为空表示删除的是叶节点
        if (replace == null) {
            this.data = null;
            if (this.parent != null) {
                if (this.parent.childL == this) {
                    this.parent.childL = null;
                } else {
                    this.parent.childR = null;
                }
                this.parent = null;
            }
        } else {
            this.data = replace.data;
            replace.parent = null;
        }
    }

    /**
     * 中序遍历
     */
    public void midOrderTraverse(BinaryTreeNode<T> root) {
        if (root == null || root.data == null) {
            return;
        }
        //LDR
        midOrderTraverse(root.childL);
        System.out.print(root.data);
        System.out.print(',');
        System.out.print(' ');
        midOrderTraverse(root.childR);
    }

    //非递归的中序遍历求和
    public int inTraverseSum(BinaryTreeNode<T> root) {
        Stack<BinaryTreeNode> st = new Stack<>();
        BinaryTreeNode<T> p = root;
        int count = 0;
        while (p != null || !st.empty()) {
            while (p != null) {
                st.push(p);
                count++;
                p = p.childL;
            }
            if (!st.empty()) {
                p = st.peek();
                st.pop();
                p = p.childR;
            }
        }
        return count;
    }

    public void MorrisIn(BinaryTreeNode<T> head) {
        if (head == null) return;
        BinaryTreeNode<T> cur = head;
        BinaryTreeNode<T> mostRight;
        while (cur != null) {
            mostRight = cur.childL;
            //【1、2、】判断Cur的左孩子是否为空
            if (cur.childL != null) {
                //不断向右寻找Cur左子树最右的节点【mostRight右节点不为空 或者 不为当前cur节点,则非最右】
                while (mostRight.childR != null && mostRight.childR != cur) {
                    mostRight = mostRight.childR;
                }
                // { 隐含意思:为空表示第一次来到该节点位置,为cur表示第二次来到该节点位置 }
                //【2、(1)、】若最右节点为空
                if (mostRight.childR == null) {
                    //{ 第一次来到该节点, 将该节右指针设为cur,表示该节点下一步将移动到cur }
                    mostRight.childR = cur;
                    cur = cur.childL;
                    continue;
                } else {
                    //【2、(2)、】若最右节点为当前节点cur
                    /** { 第二次来到该节点, 将该节点右指针设为原来的null,
                     前一步其实已经将当前cur指针指向了该节点的右节点了,
                     即当前的cur已经是当前mostright的下一步节点了} */
                    mostRight.childR = null;
                }
            } else {//当前cur没有左孩子的时候
            }
            //【---【中序遍历】: 当前指针cur要准备往右孩子走了,马上打印】
            System.out.print(cur.data);
            //【1、】Cur的左孩子为空 或者【 2、(2)、】mostright的右孩子为Cur,即第二次访问到该节点的时候
            cur = cur.childR;
        }
    }

    public static void main(String[] args) {
        BinaryTreeNode<Integer> tree = new BinaryTreeNode<>();
        int[] arr = new int[16];
        Random random = new Random();
        for (int i = 0; i < arr.length; i++) {
            arr[i] = random.nextInt(99);
            tree.add(arr[i]);
        }
        System.out.print("插入数据:");
        System.out.println(Arrays.toString(arr));
        System.out.print("数据排序:");
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
        System.out.print("二叉树序:[");
        tree.midOrderTraverse(tree);
        System.out.println();
        System.out.println(tree.inTraverseSum(tree));
        System.out.println("----");
        tree.MorrisIn(tree);
        BinaryTreeNode<Integer> del;
        for (int i = 0; i < arr.length; i++) {
            System.out.print("删除数字");
            System.out.println(arr[i]);
            del = tree.find(arr[i]);
            if (del != null) {
                del.del();
            }
            tree.midOrderTraverse(tree);
            System.out.println();
            tree.add(arr[i]);
        }
        System.out.println("逐个删除:");
        for (int i = 0; i < arr.length; i++) {
            System.out.print("删除数字");
            System.out.println(arr[i]);
            del = tree.find(arr[i]);
            if (del != null) {
                del.del();
            }
            tree.midOrderTraverse(tree);
            System.out.println();
        }
    }
}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,542评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,822评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,912评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,449评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,500评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,370评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,193评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,074评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,505评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,722评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,841评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,569评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,168评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,783评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,918评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,962评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,781评论 2 354

推荐阅读更多精彩内容