思路:后续遍历递归法;遍历左子树高度,右子树高度,最后加上根节点所在层级1
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def getDepth(self,node):
if not node:
return 0
left_depth=self.getDepth(node.left)
right_depth=self.getDepth(node.right)
return max(left_depth,right_depth)+1
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.getDepth(root)
思路:后续遍历递归法,求左子树和右子树的最小值;注意和最大深度不同的情况是,若左子树为空,深度为右子树深度加1;若右子树为空,深度为左子树深度加1
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def getDepth(self,node):
if not node:
return 0
leftDepth=self.getDepth(node.left)
rightDepth=self.getDepth(node.right)
if node.left is None and node.right is not None:
return rightDepth+1
if node.right is None and node.left is not None:
return leftDepth+1
return min(leftDepth,rightDepth)+1
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.getDepth(root)
思路:后序遍历递归。左子树节点树+右子树节点树+根节点
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def getCount(self,node):
if not node:
return 0
leftCount=self.getCount(node.left)
rightCount=self.getCount(node.right)
return leftCount+rightCount+1
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.getCount(root)