DFS:
public static int maxDepth_DFS(Node root) { if(root == null){ return 0; } else{ int intLeftTreeDepth = maxDepth_DFS(root.left); int intRightTreeDepth = maxDepth_DFS(root.right); return intLeftTreeDepth > intRightTreeDepth? intLeftTreeDepth + 1:intRightTreeDepth+ 1; } }
BFS:
public static int maxDepth_BFS(Node root) { if(root == null){ return 0; } Queue_Genericque = new Queue_Generic (1000); int nCount = 1; int nDepth = 0;// 记录队列里面每一层上的元素 que.Insert(root); while(!que.isEmpty()) { Node NodeTemp = que.PeekFront(); que.Remove(); nCount --; //if(!NodeTemp.left.equals(null)){ if(! (NodeTemp.left == null)){ que.Insert(NodeTemp.left); } //if (!NodeTemp.right.equals(null)){ if (!(NodeTemp.right==null)){ que.Insert(NodeTemp.right); } if (nCount == 0) { //System.out.println("Node Count : "+nCount); nDepth ++; nCount = que.Size(); //System.out.println("Node Count : "+nCount); } } return nDepth; }
其它知识
泛型队列:
public class Queue_Generic{ int MaxSize; T[] DataStorage; int iHeadPos; int iEndPos; int iItenCount; public Queue_Generic(int intMax){ MaxSize = intMax; iHeadPos = 0; iEndPos = -1; iItenCount = 0; DataStorage = (T[]) new Object[intMax]; } public void Insert(T value){ if(MaxSize > iItenCount){ if(iEndPos == MaxSize-1){ iEndPos = -1; } DataStorage[++iEndPos] = value; iItenCount++; } } public T Remove(){ T Temp; if(iItenCount > 0){ iItenCount--; Temp = DataStorage[iHeadPos++]; if(iHeadPos == MaxSize){ iHeadPos = 0; } } else{ return null; } return Temp; } public T Peek(){ return (T)DataStorage[iEndPos]; } public T PeekFront(){ return (T)DataStorage[iHeadPos]; } public boolean isEmpty(){ if(iItenCount == 0){ return true; }else{ return false; } } public boolean isFull(){ if(iItenCount == MaxSize){ return true; }else{ return false; } } public int Size(){ return iItenCount; }}
其中,关键的点
1. 存储结构需要将Object强制转换成泛型类型:DataStorage = (T[]) new Object[intMax];
2. 返回的结果为泛型类型: return (T)DataStorage[iEndPos];