Leetcode110
题目:判断平衡二叉树
学习资料:代码随想录
实现过程
- 判断左子树和右子树高度差不大于一
- 求高度可以利用后序遍历
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def check(root):
if root == None:
return 0
leftD = check(root.left)
if leftD == -1: return -1
rightD = check(root.right)
if rightD == -1: return -1
re = 0
if abs(leftD - rightD) >1 :
re = -1
else:
re = 1 + max(leftD, rightD)
return re
if check(root) != -1:
return True
else:
return False
Leetcode257
题目:二叉树的所有路径
学习资料: 代码随想录
实现过程
- 回溯的方法
- 注意要先将结点添加到path中,再判断,不然会漏掉叶子结点
- 这里的回溯使用字符串path,只做内容拷贝,那么回溯之后path还是原来的path,不同于list需要pop出来
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
path = ""
re = []
if not root:return root
self.backtracking(root, path, re)
return re
def backtracking(self, root, path, re):
# 中结点,叶子结点要包含上
path += str(root.val)
if not root.left and not root.right :
re.append(path[:])
if root.left:
# path 是字符串类型,path只做内容拷贝
self.backtracking(root.left, path + '->', re)
if root.right:
self.backtracking(root.right, path + '->', re)
Leetcode404
题目:左叶子之和
学习资料: 代码随想录
实现过程
- 关键如何判断是否为左叶子,需要利用父节点来判断,就是该结点的左孩子不为空,其该结点左孩子的左右孩子都为空
- 利用后序遍历来返回,左子树左叶子的个数和右子树左叶子的个数,然后中间结点来相加
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
return self.findLeftLeaves(root)
def findLeftLeaves(self, root):
if root == None:
return 0
leftLeaves = self.findLeftLeaves(root.left)
if root.left != None and root.left.left == None and root.left.right == None:
leftLeaves = root.left.val
rightLeaves = self.findLeftLeaves(root.right)
nums = leftLeaves + rightLeaves
return nums