這里演示的二叉樹為3層。
遞歸實現,先構造出一個root節點,先判斷左子節點是否為空,為空則構造左子節點,否則進入下一步判斷右子節點是否為空,為空則構造右子節點。
利用層數控制迭代次數。
依次遞歸第二段的內容。
下面是代碼,很簡單,耐心看看就懂了。
package Construct;public class ConstructTree { PRivate int count = 0; class Node { int i; Node left; Node right; public Node(int i) { this.i = i; } } public static void main(String[] args) throws Exception { ConstructTree ct = new ConstructTree(); ct.startRun(3); } public void startRun(int n) { Node root = new Node(count++); System.out.println(count - 1+" root "+n); Node current = root; Construct(current,n - 1); } public void Construct(Node current, int n) { if(n > 0) { if(current.left == null) { current.left = new Node(count++); System.out.println(count - 1+" left "+n); Construct(current.left, n - 1); } if(current.right == null) { current.right = new Node(count++); System.out.println(count - 1+" right "+n); Construct(current.right, n - 1); } } }}輸出:(下面輸出對應值)節點的數據 左節點/右節點 層數
0 root 31 left 22 left 13 right 14 right 25 left 16 right 1
新聞熱點
疑難解答