给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
Python: 递归(后序遍历)
# 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 not root:
return True
return self.postrecur(root) != -1
def postrecur(self, root:Optional[TreeNode]) -> int:
if root == None:
return 0
left_height = self.postrecur(root.left)
right_height = self.postrecur(root.right)
if abs(left_height - right_height) > 1:
return -1
# if left tree or right tree is imbalance, the whole tree is imbalance
if left_height == -1 or right_height == -1:
return -1
height = 1 + max(left_height, right_height)
return height
给你一个二叉树的根节点 root
,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
Python:
# 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]:
if not root:
return []
ans = []
path = []
self.prerecur(root, ans, path)
return ans
def prerecur(self, cur:Optional[TreeNode], ans:List[str], path:List[int]) -> List[str]:
path.append(cur.val)
# stop condition: leave node
if not cur.left and not cur.right:
ans.append("->".join(map(str,path)))
return
if cur.left:
self.prerecur(cur.left, ans, path)
path.pop() # recall, (path.append(root.val))
if cur.right:
self.prerecur(cur.right, ans, path)
path.pop()
# 迭代
class Solution:
def binaryTreePaths(self, root: 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
给定二叉树的根节点 root
,返回所有左叶子之和。(左叶子:当某个节点左孩子为叶子节点是,该左孩子为左叶子)
Python: 迭代
# 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:
ans = 0
if not root:
return ans
stack = [root]
while stack:
cur = stack.pop()
# If left children is leaf, update ans
if cur.left and not cur.left.right and not cur.left.left:
ans += cur.left.val
if cur.right: stack.append(cur.right)
if cur.left: stack.append(cur.left)
return ans