104. 二叉树的最大深度
二叉树的最大深度
这里我首先想到就是使用层序遍历,得到每层的数据,是个二维列表。长度就是深度。
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
results = []
from collections import deque
que =deque([root])
while que:
size=len(que)
res=[]
for _ in range(size):
cur=que.popleft()
res.append(cur.val)
if cur.left:
que.append(cur.left)
if cur.right:
que.append(cur.right)
results.append(res)
return len(results)
使用递归写法。后序遍历,使用后序遍历的主要原因是因为:需要把中放到最后处理。
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
return self.getDepth(root)
def getDepth(self,node):
if not node:
return 0
leftHeight = self.getDepth(node.left)#左
rightHeight = self.getDepth(node.right)#右
height = 1+max(leftHeight,rightHeight)#中
return height
559. N 叉树的最大深度
递归方法
- 传入参数
- 终止条件
- 单层逻辑
class Solution:
def maxDepth(self, root: 'Node') -> int:
if not root:
return 0 #没有节点的高度
depth =0
for i in range(len(root.children)):
depth = max(depth,self.maxDepth(root.children[i]))
return depth+1
遍历方法:队列,迭代法
与之前层序遍历的代码统一起来。
class Solution:
def maxDepth(self, root: 'Node') -> int:
from collections import deque
if not root:
return 0
que=deque([root])
depth=0
while que:#循环一次depth+1
size=len(que)
depth+=1
for i in range(size):
cur = que.popleft()
for j in range(len(cur.children)):
if cur.children[j]:
que.append(cur.children[j])
return depth
111. 二叉树的最小深度
二叉树的最小深度
有点难理解,但是要想明白递归的终止条件。
class Solution:
def minDepth(self, root) -> int:
if not root:
return 0
if not root.left and not root.right:
return 1
depth = float('inf')
# 找寻叶子结点,叶子节点是指没有子节点的节点。
if root.left:
depth=min(self.minDepth(root.left),depth)
if root.right:
depth = min(self.minDepth(root.right),depth)
return depth+1
222. 完全二叉树的节点个数
完全二叉树的节点个数
这个就是最大深度的翻版,比最大深度简单。通用方法
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
return self.getDepth(root)
def getDepth(self,node):
if not node:
return 0
leftHeight = self.getDepth(node.left)
rightHeight = self.getDepth(node.right)
return leftHeight+rightHeight+1
适用于完全二叉树的方法。
class Solution:
def countNodes(self, root: TreeNode) -> int:
if not root:
return 0
left = root.left
right = root.right
leftDepth = 0 #这里初始为0是有目的的,为了下面求指数方便
rightDepth = 0
while left: #求左子树深度
left = left.left
leftDepth += 1
while right: #求右子树深度
right = right.right
rightDepth += 1
if leftDepth == rightDepth:
return (2 << leftDepth) - 1 #注意(2<<1) 相当于2^2,所以leftDepth初始为0
return self.countNodes(root.left) + self.countNodes(root.right) + 1