描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
示例1
输入:
{1,2,3,4,5,#,6,#,#,7}
复制
返回值:
4
思路1:分治
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int TreeDepth(TreeNode root) {
int depth = 0;
int maxDepth = 0;
if(root == null){
return depth;
}
int ldepth = TreeDepth(root.left);
int rdepth = TreeDepth(root.right);
if(ldepth >= rdepth){
depth = ldepth + 1;
}else{
depth = rdepth + 1;
}
return depth;
}
}
思路2: BFS
import java.util.LinkedList;
import java.util.Queue;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int TreeDepth(TreeNode root) {
int depth = 0;
if(root == null){
return depth;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
for(int i = 0; i < size; i++){
TreeNode node = queue.poll();
if(node.left != null){
queue.offer(node.left);
}
if(node.right != null){
queue.offer(node.right);
}
}
depth++;
}
return depth;
}
}