樹的左視圖(Java)

問題描述:

二叉樹的節點按照從上到下,從左到右,從1開始編號,其中空着的節點用“#”表示。輸出樹的左視圖,如:
輸入:1 2 3 # 4 5 6 # # # # 7 8
輸出:1 2 4 7
在這裏插入圖片描述

public class LeftViewTree {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int i= 0; //當前多少層
        int j = 0; //當前層的第幾個節點
        boolean flag = false; //是否找到當層的第一個非空節點

        while(in.hasNext()) {
            i = i+1;
            j = 1;
            flag = false;

            while(j <= Math.pow(2,i-1)) {
                if(!in.hasNext())
                    return;
                String s = in.next();
                if(flag == false && !s.equals("#")){
                    System.out.print(s + " ");
                    flag = true;

                }
                j++;
            }

        }

    }
}

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