代码随想录算法训练营|110.平衡二叉树;257. 二叉树的所有路径;404.左叶子之和
110.平衡二叉树
题目链接: 110.平衡二叉树
文档讲解: 代码随想录
题目难度:中等
思路: 递归法,求解各叶子节点深度差,前序遍历
时间复杂度:O(n);空间复杂度:O(1)
下面展示 代码
:
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def getHeight(self, current):
if current == None:
return 0
leftheight = self.getHeight(current.left)
if leftheight == -1:
return -1
rightheight = self.getHeight(current.right)
if rightheight == -1:
return -1
if abs(leftheight - rightheight) <= 1:
return 1 + max(leftheight, rightheight)
else:
return -1
def isBalanced(self, root: Optional[TreeNode]) -> bool:
if root == None:
return True
else:
height = self.getHeight(root)
if height == -1:
return False
else:
return True
257. 二叉树的所有路径
题目链接: [257. 二叉树的所有路径](https://leetcode.cn/problems/binary-tree-paths/)
文档讲解: 代码随想录
题目难度:中等
思路: 根节点到所有叶子节点的路径,前序遍历
时间复杂度:O(n);空间复杂度:O(n)
代码
如下
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def backtracking(self, cur, path, res):
if cur == None:
return
path.append(cur.val)
if cur.left == None and cur.right == None:
sPath = '->'.join(map(str, path)) # 列表转换为字符
res.append(sPath)
return
if cur.left:
self.backtracking(cur.left, path, res)
path.pop()
if cur.right:
self.backtracking(cur.right, path, res)
path.pop()
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
if root == None:
return []
else:
res = []
self.backtracking(root, [],res)
return res
404.左叶子之和
题目链接: 404.左叶子之和
文档讲解: 代码随想录
题目难度:中等
思路: 左子树左叶子和+右子树左叶子和,因此采用后序遍历
时间复杂度:O(n);空间复杂度:O(1)
代码
如下
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
# 递归法
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
if root == None:
return 0
if root.left == None and root.right == None:
return 0
# 后序遍历
left = self.sumOfLeftLeaves(root.left)
right = self.sumOfLeftLeaves(root.right)
if root.left and root.left.left == None and root.left.right == None:
# 左叶子
left += root.left.val
res = left + right
return res