線索二叉樹——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;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章