1,题目大意:
有一棵二叉树,求它的深度
2,思路:
(1)树与二叉树的区别:
树与二叉树是不同的数据结构,不是一样的,树不能为空,而二叉树可以。
(2)找二叉树的深度:
常用的想到的有DFS,BFS两种方法。BFS相对复杂点(构造一个队列),这里用DFS的方法。
(3)DFS方法:深度搜索
left:二叉树左子树深度
right:二叉树右子树深度
lenght:二叉树深度max(left,right) + 1
(4)有一个临界点
二叉树为空的时候,深度为0
3,代码
public class C104 {
public static void main(String[] args) {
TreeNode tNode1 = new TreeNode();
tNode1.left = new TreeNode();
System.out.println(maxDepth(tNode1));
}
public static int maxDepth(TreeNode root) {
if (root == null) {
return 0;
} else {
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return 1 + (left > right ? left : right);
}
}
}
class TreeNode {
TreeNode left;
TreeNode right;
TreeNode() {
this.left = null;
this.right = null;
}
}
(2)python
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None: return 0
leftDepth = self.maxDepth(root.left)
rightDepth = self.maxDepth(root.right)
return leftDepth + 1 if leftDepth > rightDepth else rightDepth + 1
4,缺点:时间不是很快,大家可以提出更好的方法。