首页 > 其他 > 详细

binary tree

时间:2018-08-04 15:36:09      阅读:155      评论:0      收藏:0      [点我收藏+]

中序线索化

二叉树节点定义:

class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    int isleftChild = 1;//0:线索 1:左孩子
    int isrightChild = 1;

    public TreeNode(int val) {
        this.val = val;
    }
}

在中序遍历的过程中完成线索化

   //preNode始终指向中序序列中前一个访问的节点
    private static TreeNode preNode = null;//只能用全局变量的形式来记录。

    //curNode始终指向中序序列中当前访问的节点
    public static TreeNode inIOrderThread(TreeNode curNode) {
        if (curNode == null)
            return null;

        //线索化左子树
        InClueTree(curNode.left);

        //线索化当前节点
        if (curNode.left == null) {
            curNode.isleftChild = 0;
            curNode.left = preNode;
        }
        if (preNode != null && preNode.right == null) {
            preNode.isrightChild = 0;
            preNode.right = curNode;
        }
        preNode = curNode;//

        //线索化右子树
        InClueTree(curNode.right);

        return curNode;
    }

遍历中序线索二叉树

public static void inOrderThreadTravel(TreeNode root) {
        while (root != null) {
                System.out.print(root.val + " ");
            //存在线索,root的直接后继就是root.rigth;
            if (root.isrightChild == 0) {
                root = root.right;
            }
            //不存在线索的时候一定存在孩子节点,则root的直接后继就是其右子树的中序第一个元素。
            else {
                root = root.right;
                while (root.left != null && root.isleftChild == 1) {
                    root = root.left;
                }
            }
        }
    }

 

binary tree

原文:https://www.cnblogs.com/arjenlee/p/9418697.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!