第一题
给定一个二叉树,返回其节点值自底向上的层次遍历。
解
class Solution:
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
stack = [root]
res = []
while stack:
next_stack = []
temp_val = []
for node in stack:
temp_val.append(node.val)
if node.left:
next_stack.append(node.left)
if node.right:
next_stack.append(node.right)
stack = next_stack
res.insert(0,temp_val)
return res
第二题
给定一个二叉树,返回所有从根节点到叶子节点的路径。
解
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
if not root:
return []
if not root.left and not root.right:
return [str(root.val)]
paths = []
if root.left:
for i in self.binaryTreePaths(root.left):
paths.append(str(root.val)+'->'+i)
if root.right:
for i in self.binaryTreePaths(root.right):
paths.append(str(root.val)+'->'+i)
return paths
第三题
给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
class Solution:
def findMode(self, root: TreeNode) -> List[int]:
vals = []
if not root:
return []
def trace(root):
if not root:
return
vals.append(root.val)
if root.left:
trace(root.left)
if root.right:
trace(root.right)
trace(root)
from collections import Counter
res = []
c = Counter(vals)
maxcount = c.most_common(1)[0][1]
for i in c.most_common():
if i[1]==maxcount:
res.append(i[0])
return res