代码随想录|二叉树part02 |226.反转二叉树 101.对称二叉树 104.二叉树的最大深度 111.二叉树的最小深度
python
一、226.反转二叉树
反转肯定是同一层的先翻转完再翻转其他层,所以不能用中序遍历(父节点放在中间遍历)
反转了之后还得输出呢!!
1.核心代码
代码如下(示例):
class Solution:
def invertTree(self,root):
if not root:
return None
root.left, root.right=root.right,root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
2.输入输出
二叉树的输入输出还是有问题:
import collections
class TreeNode:
def __init__(self,val,left=None,right=None):
self.val=val
self.left=left
self.right=right
class Solution:
def invertTree(self,root):
if not root:
return None
root.left, root.right=root.right,root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
def buildTree(data,root,i,n):
if i<n:
if data[i] != "null":
root=TreeNode(int(data[i]))
i=2*i+1
root.left=buildTree(data,None,i,n)
i=i+1
root.right = buildTree(data, None , i, n)
return root
def LevelOrder(root):
if not root:
return []
queue = collections.deque([root])
level=[]
while queue:
n=len(queue)
for _ in range(n):
cur = queue.popleft()
level.append(cur.val)
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
return level
if __name__=="__main__":
input_root=input().strip("[]")
if input_root:
parts=input_root.split(",")
root=buildTree(parts,None,0,len(parts))
solution=Solution()
result=solution.invertTree(root)
invertroot=LevelOrder(result)
print(invertroot)
1 不能二叉树的输入直接用list转为int形式,因为存在null
2 inital二叉树,要令left 和 right为None
3 对root操作,要先判断是否为null
4 还有输出的问题,要加一个层序输出的函数
3.问题
二、101.对称二叉树
1.核心代码
代码如下(示例):
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
return self.compare(root.left, root.right)
def compare(self,left,right):
if left==None and right!=None: return False
if right==None and left!=None: return False
if left==None and right==None: return True
if left.val != right.val: return False
outside = self.compare(left.left,right.right)
inside = self.compare(left.right,right.left)
return outside and inside
不难,但是是先看了代码然后复现出来的
2.输入输出
class TreeNode:
def __init__(self,val,left=None,right=None):
self.val=val
self.left=left
self.right=right
class Solution:
def isSymmetric(self,root):
if not root:
return True
return self.compare(root.left,root.right)
def compare(self,left,right):
if left==None and right!=None: return False
if right==None and left!=None: return False
if right==None and left==None: return True
if left.val != right.val: return False
outside=self.compare(left.left, right.right)
inside=self.compare(left.right, right.left)
return outside and inside
def buildtree(part,root,i,n):
if i<n:
if part[i] != "null":
root=TreeNode(int(part[i]))
i=2*i+1
root.left=buildtree(part,None,i,n)
i=i+1
root.right=buildtree(part,None,i,n)
return root
if __name__=="__main__":
input_root=input().strip("[]")
if input_root:
part=input_root.split(",")
root=buildtree(part,None,0,len(part))
solution=Solution()
result=solution.isSymmetric(root)
print(result)
三、104.二叉树的最大深度
1.核心代码
代码如下(示例):
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
return 1+max(self.maxDepth(root.left),self.maxDepth(root.right))
这题有非常多的解法,但是我调了一个最简单的记。后面有时间再看其他的解法
2.输入输出
class TreeNode:
def __init__(self,val,left=None,right=None):
self.val=val
self.left=left
self.right=right
class Solution:
def maxDepth(self,root):
if not root:
return 0
return 1+max(self.maxDepth(root.left),self.maxDepth(root.right))
def buildTree(part,root,i,n):
if i<n:
if part[i] != "null":
root=TreeNode(int(part[i]))
i=2*i+1
root.left=buildTree(part,None,i,n)
i=i+1
root.right=buildTree(part,None,i,n)
return root
if __name__=="__main__":
parts=input().strip("[]")
if parts:
part=parts.split(",")
root=buildTree(part,None,0,len(part))
solution=Solution()
result=solution.maxDepth(root)
print(result)
代码自己写时遇到的小错误:root.left=buildTree(part,None,i,n)没有加 root.left=,导致root没有子节点,笑死
四、111.二叉树的最小深度
111.二叉树的最小深度
深度从从上往下,
高度时从下往上
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。注意是叶子节点。
叶子节点:是指左右孩子都不存在的节点
1.核心代码
代码如下(示例):
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
if not root.left:
return 1+self.minDepth(root.right)
if not root.right:
return 1+self.minDepth(root.left)
return 1+min(self.minDepth(root.left),self.minDepth(root.right))
主要是注意只有一遍子树的特殊情况
2.输入输出
原来的输入是错的!!,每一个子节点如果没有的话,都要输入一个null。
但是实际leetcode给的输入,
比如:root = [2,null,3,null,4,null,5,null,6]。
这实际上说明,null节点的子节点是肯定没有的,所以就省略了这个下面节点的输入,但是给我的处理带来了麻烦
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def minDepth(self, root):
if not root:
return 0
if not root.left and not root.right:
return 1
if not root.left:
return 1 + self.minDepth(root.right)
if not root.right:
return 1 + self.minDepth(root.left)
return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
def buildTree(parts):
if not parts:
return None
# 初始化根节点
root = TreeNode(int(parts[0]))
queue = [root]
idx = 1
while queue and idx < len(parts):
current = queue.pop(0)
# 构建左子树节点
if idx < len(parts) and parts[idx] != "null":
current.left = TreeNode(int(parts[idx]))
queue.append(current.left)
idx += 1
# 构建右子树节点
if idx < len(parts) and parts[idx] != "null":
current.right = TreeNode(int(parts[idx]))
queue.append(current.right)
idx += 1
return root
if __name__ == "__main__":
parts = input().strip('[]').split(',')
if parts == ['']:
parts = []
root = buildTree(parts)
solution = Solution()
result = solution.minDepth(root)
print(result)
非常恶心的二叉树,已经对输入要吐血了
总结
输入输出