二叉樹按層遍歷列印
阿新 • • 發佈:2018-12-13
二叉樹按層進行遍歷,例如:
① ② ③ ④ ⑤ ⑥ 進行按層遍歷的話列印就是:
1
2 3
4 5 6
思路:
用一個current來表示當前指標,用nextLastRight來表示最右節點的指標,例如,current一開始指向1,而下一行的nextLastRight指標指向子節點的最右邊,假如沒有右子樹,nextLastRight就指向左子樹。
下面看看程式碼:
package com.lxj.binarytree; import java.util.Queue; import java.util.Scanner; import java.util.concurrent.ArrayBlockingQueue; public class Tree { private Tree left; private Tree right; private int value; public int getValue() { return this.value; } public void setValue(int value) { this.value = value; } public void setLeft(Tree left) { this.left = left; } public void setRight(Tree right) { this.right = right; } public Tree getLeft() { return this.left; } public Tree getRight() { return this.right; } public static void main(String []args) throws InterruptedException { Test test = new Test(); Tree head = new Tree(); test.buildTree(head); // System.out.println(head); // test.pre(head); //二叉樹按層遍歷 test.layerForeach(head); // test.pre(head); } } /*二叉樹寬度按層遍歷 ① ② ③ ④ ⑤ ⑥ 0 0 0 0 0 0 0 1 2 4 -1 -1 5 -1 -1 3 6 -1 -1 -1 */ class Test{ public void layerForeach(Tree head) throws InterruptedException { ArrayBlockingQueue<Tree> queue = new ArrayBlockingQueue<>(20); Tree curr = head; Tree nextLast = head; queue.put(head); while(head != null) { curr = head; if(head.getLeft() != null) { queue.put(head.getLeft()); } if(head.getRight() != null) { queue.put(head.getRight()); } //如果當前節點等於最右節點則進行換行 int temp = queue.poll().getValue(); //假如是最右節點則進行換行 if(curr == nextLast) { if(temp != 0) { System.out.println(temp); } //找到最右節點 if(curr.getRight() != null) { nextLast = curr.getRight(); }else { nextLast = curr.getLeft(); } }else { if(temp != 0) { System.out.print(temp + " "); } } //更新head值,但不出佇列 head = queue.peek(); } } //構建二叉樹,0代表為空 public void buildTree(Tree head) { Scanner sc = new Scanner(System.in); int t; if(( t = sc.nextInt()) != -1) { head.setValue(t); head.setLeft(new Tree()); head.setRight(new Tree()); buildTree(head.getLeft()); buildTree(head.getRight()); }else { head = null; } } //二叉樹的先序遍歷 public void pre(Tree head) { if(head != null) { System.out.println(head.getValue()); pre(head.getLeft()); pre(head.getRight()); } } }