线索二叉树——Java

package tree;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;

public class Tree {

    /*
    * 线索化二叉树,中序
    * */
    public static Note treading(Note t) {
        if (t == null) return null;
       Stack<Note> s = new Stack<>();
       Note head = new Note();
       head.left = t;
       head.right = null;
       head.rfag = 1;
       Note pre = head;
       s.push(t);
       t = t.left;
        while (!s.isEmpty() || t != null) {
            while(t != null) {
                s.push(t);
                t = t.left;
            }
            t = s.pop();
            if (t.left == null) {
                t.left = pre;
                t.lfag = 1;
            }
            if (pre.right == null) {
                pre.right = t;
                pre.rfag = 1;
            }
            pre = t;
            t = t.right;
        }
        pre.rfag = 1;
        pre.right = head;
        return head;
    }

    /*
    * 遍历线索二叉树
    * */
    public static void show(Note head) {
        Note p = head.right;
        while(p != head) {
            System.out.print(p.data);
            if (p.rfag != 1) {
                p = p.right;
                while (p.lfag != 1) {
                    p = p.left;
                }
            } else {
                p = p.right;
            }
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.next();
        Queue<Character> que = new LinkedList<>();   //因为Java中没有一次读取一个字符的机制所以我把整个字符串整个读进来然后一个字符一个字符的添加到队列,在使用的时候依次拿出
        for (int i = 0;i < s.length(); i ++) {
            que.add(s.charAt(i));
        }
        Note tree = createTree(que);
        Note head = treading(tree);
        show(head);
    }
    static class Note {
        public char data;
        public Note left = null;
        public Note right = null;
        public int lfag;
        public int rfag;
    }
}

发布了57 篇原创文章 · 获赞 55 · 访问量 1943

猜你喜欢

转载自blog.csdn.net/qq_40561126/article/details/104376339