我用下圖的樹爲例,作樹的遍歷:java
樹節點的定義:算法
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
public TreeNode(int val, TreeNode left, TreeNode right) {
super();
this.val = val;
this.left = left;
this.right = right;
}}樹的結構的代碼實現:public static void main(String[] args) {
TreeNode e = new TreeNode(1);
TreeNode g = new TreeNode(2);
TreeNode h = new TreeNode(3);
TreeNode i = new TreeNode(4);
TreeNode d = new TreeNode(5,null,g);
TreeNode f = new TreeNode(6,h,i);
TreeNode b = new TreeNode(7,d,e);
TreeNode c = new TreeNode(8,f,null);
TreeNode root = new TreeNode(9,b,c);}
複製代碼
public static void printTree(TreeNode t){
if(t!=null){
printTree(t.left);
System.out.print(t.val+" ");
printTree(t.right);
}
}
複製代碼
輸出結果: 5 2 7 1 9 3 6 4 8bash
public static void printTree(TreeNode t){
if(t!=null){
printTree(t.left);
printTree(t.right);
System.out.print(t.val+" ");
}
}
複製代碼
輸出結果: 2 5 1 7 3 4 6 8 9ui
public static void printTree(TreeNode t){
if(t!=null){
System.out.print(t.val+" ");
printTree(t.left);
printTree(t.right);
}
}
複製代碼
輸出結果: 9 7 5 2 1 8 6 3 4this
有沒有以爲樹的先序,中序,後序遍歷都很是簡單,遞歸三行代碼就搞定了。好吧,下邊厲害的要來了spa
層序遍歷:全部深度爲D的節點要在深度爲D+1的節點以前進行處理,層序遍歷與其餘類型的遍歷不一樣的地方在於它不是遞歸地執行的,它用到隊列,而不使用遞歸所默示的棧。code
算法思想:cdn
package Tree;import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.Queue;/* * 層序遍歷 * */public class TreePrinter1 {
public static int[][] printTree(TreeNode root) {
List< List<Integer> > list = new ArrayList< List<Integer> >();
list.add(new ArrayList<Integer>());
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
TreeNode lastNode = root; // 當前行最右節點
TreeNode nlastNode = root; // 下一行最右節點
TreeNode tmpNode = null;
int hight = 0; // 樹的高度
while(!queue.isEmpty()){
tmpNode = queue.poll();
if(tmpNode!=null){
list.get(hight).add(tmpNode.val);
}
if(tmpNode.left!=null){
queue.add(tmpNode.left);
nlastNode = tmpNode.left;
}
if(tmpNode.right!=null){
queue.add(tmpNode.right);
nlastNode = tmpNode.right;
}
if(tmpNode == lastNode){
lastNode = nlastNode;
hight++;
list.add(new ArrayList<Integer>());
}
}
int[][] data = new int[list.size()][];
for(int i=0;i<list.size();i++){
for(int j=0;j<list.get(i).size();j++){
data[i][j] = list.get(i).get(j);
}
}
return data;
}
public static void main(String[] args) {
TreeNode e = new TreeNode(1);
TreeNode g = new TreeNode(2);
TreeNode h = new TreeNode(3);
TreeNode i = new TreeNode(4);
TreeNode d = new TreeNode(5,null,g);
TreeNode f = new TreeNode(6,h,i);
TreeNode b = new TreeNode(7,d,e);
TreeNode c = new TreeNode(8,f,null);
TreeNode root = new TreeNode(9,b,c);
int[][] data =TreePrinter.printTree(root);
for(int s=0;s<data.length;s++){
for(int j=0;j<data[s].length;j++){
System.out.print(data[s][j]+" ");
}
System.out.println();
}
}}
複製代碼
輸出結果: 9 7 8 5 1 6 2 3 4blog