513. 找树左下角的值(其实就是按层遍历二叉树)
class Solution(object):
def findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return
stack = [root]
while stack:
stack1 = []
x = stack[0].val
while stack:
a = stack.pop(0)
if a.left:
stack1.append(a.left)
if a.right:
stack1.append(a.right)
stack = stack1
return x
515. 在每个树行中找最大值(非递归版本)
class Solution(object):
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return
res = []
stack = [root]
while stack:
stack1 = []
max1 = stack[0].val
while stack:
a = stack.pop(0)
max1 = max(max1,a.val)
if a.left:
stack1.append(a.left)
if a.right:
stack1.append(a.right)
res.append(max1)
stack = stack1
return res
递归版本:
class Solution(object):
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
#递归
res = []
self.getval(res,root,0)
return res
def getval(self,res,root,deep):
if not root:
return
if len(res) == deep:
res.append(root.val)
elif res[deep]< root.val:
res[deep] = root.val
self.getval(res,root.left,deep+1)
self.getval(res,root.right,deep+1)