题目:输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
递归解法:
public int TreeDepth(TreeNode root) {
if(root == null) return 0;
return Math.max(TreeDepth(root.left),TreeDepth(root.right))+1;
}
非递归解法
public class Solution {
public int TreeDepth(TreeNode root) {
if(root == null) return 0;
Queue<TreeNode> q = new LinkedList();
q.offer(root);
int count = 0;
while(!q.isEmpty()){
int size = q.size();
for(int i=0;i<size;i++){
root = q.poll();
if(root.left != null)
q.offer(root.left);
if(root.right != null)
q.offer(root.right);
}
count++;
}
return count;
}
}