今天的题和昨天差不多,都是用dfs或者bfs去遍历
104. Maximum Depth of Binary Tree
这道题还是遍历,只不过求得是深度不是node的顺序了
Way1:
直接前序遍历:
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
return max(self.maxDepth(root.left),self.maxDepth(root.right))+1
Way2:
用bfs算有几层:
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
q=deque()
if not root:
return 0
res=0
q.append(root)
while q:
res+=1
for _ in range(len(q)):
node=q.popleft()
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return res
111. Minimum Depth of Binary Tree
这道题是上一道题的变种,也一样可以用前序递归或者去做
Way1:
递归过程中找左右子树最少的然后加1为当前节点的最小的deepth
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
if not root.left:
return self.minDepth(root.right)+1
if not root.right:
return self.minDepth(root.left)+1
else:
return min(self.minDepth(root.left),self.minDepth(root.right))+1
Way2:
还是用deque去做.这次判断要是有个node没有左右子树,则返回值
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
q=deque()
if not root:
return 0
res=0
q.append(root)
while q:
res+=1
for _ in range(len(q)):
node=q.popleft()
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
if not node.left and not node.right:
return res
222. Count Complete Tree Nodes
首先完全二叉树一定包括多个小的满二叉树,可以用满二叉树的性质去做.判断满二叉树即一直递归左子树的deepth和一直递归右子树的deepth的值是相同的
Way1:
每次都算出左右的深度然后做递归
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
l=root.left
r=root.right
deepth_l=0
deepth_r=0
while l:
l=l.left
deepth_l+=1
while r:
r=r.right
deepth_r+=1
if deepth_r==deepth_l:
return (2**(deepth_l+1))-1
return self.countNodes(root.left) + self.countNodes(root.right)+1