Java 按深度列印二叉樹
阿新 • • 發佈:2019-01-23
二叉樹的列印程式需要用到佇列來完成,在Java中使用LinkedList類即可。具體的程式碼如下所示:
在TreeNode類中除了成員之外還有一個新增節點的函式,用遞迴即可完成數的建立。public class TreeNode { private int value; private TreeNode ltr; private TreeNode rtr; public TreeNode addNode(int value) {//給一個樹加一個節點,this表示樹根 TreeNode root =this; if (this.getValue() > value) { if(this.getLtr()!=null) { this.setLtr(this.getLtr().addNode(value)); } else { TreeNode tnew = new TreeNode(value); tnew.setLtr(null); tnew.setRtr(null); this.setLtr(tnew); } } else { if(this.getRtr()!=null) { this.setRtr(this.getRtr().addNode(value)); } else { TreeNode tnew = new TreeNode(value); tnew.setLtr(null); tnew.setRtr(null); this.setRtr(tnew); } } return root; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public TreeNode getLtr() { return ltr; } public void setLtr(TreeNode ltr) { this.ltr = ltr; } public TreeNode getRtr() { return rtr; } public void setRtr(TreeNode rtr) { this.rtr = rtr; } public TreeNode() { } public TreeNode(int value) { this.value = value; } }
測試類如下,列印每一層的樹節點後,會換行後列印下一深度的節點。
import java.util.LinkedList; import java.util.Scanner; public class TreePrinter { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); String[] set = s.split(" "); TreeNode t = new TreeNode(Integer.parseInt(set[0])); for (int i = 1; i < set.length; i++) { t.addNode(Integer.parseInt(set[i])); } sc.close(); System.out.println("樹已經建立完畢,按深度列印的結果為:"); LinkedList<TreeNode> lini = new LinkedList<TreeNode>(); lini.add(t); while(lini.size()!=0) { lini=printTreeInDepth(lini); } } private static LinkedList<TreeNode> printTreeInDepth(LinkedList<TreeNode> l) { // l是當前的佇列,每次要把它打完,然後對於其中的元素,加入左右兒子進入一個新的佇列,返回這個佇列 LinkedList<TreeNode> res = new LinkedList<TreeNode>();// 要返回這個佇列 for (TreeNode tn : l) { System.out.print(tn.getValue() + " "); if (tn.getLtr() != null) { res.add(tn.getLtr()); } if (tn.getRtr() != null) { res.add(tn.getRtr()); } } System.out.println(); return res; } }