尚硅谷Java数据结构--线索化二叉树

package DataStructure;

public class ThreadedBinaryTreeDemo {
    public static void main(String[] args) {
        Node n3=new Node(8);
        Node n4=new Node(10);
        Node n5=new Node(14);
        Node n1=new Node(3,n3,n4);
        Node n2=new Node(6);
        n2.left=n5;
        Node root=new Node(1,n1,n2);
        BinaryTree tree=new BinaryTree();
        tree.setRoot(root);

        tree.threadedNodes();
        //对二叉树进行线索化
        //todo 注意:即使是线索化之后,也不是所有的指针都得到了利用,有一些节点没有前驱或没有后继节点

        System.out.println(n5);
        System.out.println(n5.left);
        System.out.println(n5.right);
        //tree.infixOrder(root);
    }
}

class Node {
    public int val;
    public Node left;
    public Node right;
    //todo leftType==0 左子树 1 前驱节点
    public int leftType;
    public int rightType;

    public Node() {

    }

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

    public Node(int val, Node left, Node right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
    public String toString(){
        return "val="+val+" leftType="+leftType+" rightType="+rightType;
    }
}

//todo 定义二叉树
class BinaryTree {
    private Node root;
    public Node pre=null;//指向前驱节点
    public Node post=null;
    public void setRoot(Node root) {
        this.root = root;
    }
    public void infixOrder(Node node){
        if(node==null) return ;
        if(node.left!=null) infixOrder(node.left);
        System.out.println(node);
        if(node.right!=null) infixOrder(node.right);
    }
    //进行重载 使代码简洁
    public void threadedNodes(){
        this.threadedNodes(root);
    }
    //中序线索化二叉树
    public void threadedNodes(Node node) {
        if (node == null) return;
        //左子树
        if (node!=null && node.left != null) threadedNodes(node.left);
        //父节点
        if (node!=null && node.leftType == 0 && node.left==null){
            //指向前驱节点
            node.left=pre;
            node.leftType=1;
        }
        if(pre!=null && pre.rightType==0 && pre.right==null){
            //指向后继结点
            //让前驱节点的右指针指向当前节点
            // todo 前驱节点和后继结点是一对相对的概念
            pre.right=node;
            pre.rightType=1;
        }
        pre=node;
        //右子树
        if (node.right != null) threadedNodes(node.right);
    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值