104. Maximum Depth of Binary Tree
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root: return 0
return 1 + max(self.maxDepth(root.left),self.maxDepth(root.right))
111
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root: return 0
if root.left and not root.right: return 1+ self.minDepth(root.left)
if root.right and not root.left: return 1 + self.minDepth(root.right)
return 1 + min(self.minDepth(root.left),self.minDepth(root.right))
222.
from collections import deque
class Solution(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
res = 0
que = deque([root])
while que:
for i in range(len(que)):
t = que.popleft()
if t and t.left:que.append(t.left)
if t and t.right:que.append(t.right)
res +=1
return res