今天的题如果用recursion去做的话,相对都很容易
101. Symmetric Tree
这道题就是直接递归的同时传两个node即可
Way1:
直接遍历左子树和右子树,每次查看对应的node是不是一样的
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
def same(l,r):
if l and not r:
return False
if not l and r:
return False
if not l and not r:
return True
if l.val!=r.val:
return False
return same(l.left,r.right) and same(l.right,r.left)
return same(root.left,root.right)
100. Same Tree
这道题就是上一题的改编
Way1:
直接遍历两个树,每次查看对应的node是不是一样的
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
def same(l,r):
if not l and not r:
return True
if l and not r:
return False
if not l and r:
return False
if r.val!=l.val:
return False
return same(l.left,r.left) and same(l.right,r.right)
return same(p,q)
572. Subtree of Another Tree
这道题还是上一题的改编,但是要注意当找到root的时候,不是要完全比较整个tree,也有可能subtree只有一个node
Way1:
每次找root,当找到的时候进行tree的比较且进行root的比较
class Solution:
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
def same(l,r):
if not l and not r:
return True
if l and not r:
return False
if not l and r:
return False
if r.val!=l.val:
return False
return same(l.left,r.left) and same(l.right,r.right)
def getroot(root,subroot):
if not root:
return False
return getroot(root.left,subroot) or getroot(root.right,subroot) or same(root,subroot)
return getroot(root,subRoot)
226. Invert Binary Tree
还是用递归的方法,每次遍历左右子树的时候直接改值,然后继续用前序遍历
Way1:
要注意潘丹条件root不是None
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
root.left,root.right=root.right,root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root