數據結構-二叉樹相關問題及解答【3】

 

1,根據字符串輸出一個【前,中,後,層】二叉排序樹

  在某個存儲介質以以下的形式保存一顆二叉樹java

1(2(3,4(,5)),6(7,))

觀察後發現,每一個節點的格式爲ide

X,X能夠爲空this

或者X(Y,Z),其中X不能夠爲空spa

請輸出上述二叉樹的前、中、後、層遍歷。code

package com.cnblogs.mufasa.demo1;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

class Node{
    int l;
    int r;
    public Node(int l,int r){
        this.l=l;
        this.r=r;
    }
}

public class myTree {
    String str;
    String ans;
    Queue<Node> queue= new LinkedList<Node>();
    public myTree(String str){
        this.str=str;
    }
    public String normalOut(){
        ans="";
        int len=str.length();
        deal(0,len-1);
        return ans;
    }

    private void deal(int l,int r){
        if(l>r){
            return;
        }
        int cont=0,mid=-1;
        for(int i=l+2;i<r;i++){//示例:1(2(3,4(,5)),6(7,))
            if(str.charAt(i)=='(')
                cont++;

            if(str.charAt(i)==','&& cont==0){
                mid=i;
                break;
            }

            if(str.charAt(i) == ')')
                cont--;
        }
        if(mid!=-1){
            ans=ans+str.charAt(l);//前序遍歷
            deal(l+2,mid-1);
//            ans=ans+str.charAt(l);//中序遍歷
            deal(mid+1,r-1);
//            ans=ans+str.charAt(l);//後續遍歷
        }else {
            ans=ans+str.charAt(l);
        }
    }

    public String leveOut(){
        ans="";
        int len=str.length();
        queue.add(new Node(0,str.length()-1));
        while (queue.size()!=0){
            deal1();
        }
        return ans;
    }

    private void deal1(){
        Node pre=queue.poll();
        int l=pre.l,r=pre.r;
        if(l>r){
            return;
        }
        int cont=0,mid=-1;
        for(int i=l+2;i<r;i++){//示例:1(2(3,4(,5)),6(7,))
            if(str.charAt(i)=='(')
                cont++;

            if(str.charAt(i)==','&& cont==0){
                mid=i;
                break;
            }

            if(str.charAt(i) == ')')
                cont--;
        }
        if(mid!=-1){
            ans=ans+str.charAt(l);//層級遍歷
            queue.add(new Node(l+2,mid-1));
            queue.add(new Node(mid+1,r-1));
        }else {
            ans=ans+str.charAt(l);
        }
    }


    public static void main(String[] args){
        String str="1(2(3,4(,5)),6(7,))";
        myTree tree=new myTree(str);
        System.out.println(tree.normalOut());
        System.out.println(tree.leveOut());
    }
}
View Code

 

2,其餘問題待

相關文章
相關標籤/搜索