110.平衡二叉树
当一个节点不满足时,result返回-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 isBalanced(self, root: Optional[TreeNode]) -> bool:
if self.get_height(root)!=-1:
return True
else:
return False
def get_height(self,root):
if not root:
return 0#空值返回0,遇到空节点为终止
left=self.get_height(root.left)
right=self.get_height(root.right)
if left==-1 or right==-1 or abs(left-right)>1:
return -1
return max(left,right)+1
257.二叉树的所有路径
# 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 binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
#递归加回溯
result=[]
path=[]
if not root:
return result
self.traversal(root,path,result)
return result
def traversal(self,cur,path,result):
path.append(cur.val)#中,最后一个节点也要入path
if not cur.left and not cur.right:#到达叶子节点
sPath='->'.join(map(str,path))#转换为字符串
result.append(sPath)
return
if cur.left:#左
self.traversal(cur.left,path,result)
path.pop()#回溯
if cur.right:
self.traversal(cur.right,path,result)
path.pop()
迭代法
# 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 binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
stack,path_st,result=[root],[str(root.val)],[]
while stack:
cur=stack.pop()
path=path_st.pop()
if not(cur.left or cur.right):#不是叶子节点
result.append(path)
if cur.right:
stack.append(cur.right)
path_st.append(path+'->'+str(cur.right.val))
if cur.left:
stack.append(cur.left)
path_st.append(path+'->'+str(cur.left.val))
return result
左叶子之和:通过二叉树来判断,平时我们解二叉树的题目时,已经习惯了通过节点的左右孩子判断本节点的属性,而本题我们要通过节点的父节点判断本节点的属性。
# 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 is None:
return 0#遍历到空节点
if root.left is None and root.right is None:#叶子节点
return 0
leftValue=self.sumOfLeftLeaves(root.left)
if root.left and not root.left.left and not root.left.right:
#左子树是左叶子的情况
leftValue=root.left.val
rightValue=self.sumOfLeftLeaves(root.right)#中
sum_val=leftValue+rightValue
return sum_val
迭代法
# 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 is None:
return 0#遍历到空节点
st=[root]
result=0
while st:
node=st.pop()
if node.left and node.left.left is None and node.left.right is None:
result+=node.left.val
if node.left:
st.append(node.left)
if node.right:
st.append(node.right)
return result