513. Find Bottom Left Tree Value
用层序遍历( 迭代法)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
import collections
class Solution(object):
def findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
queue = collections.deque()
queue.append(root)
result = 0
while queue:
for i in range(len(queue)):
node = queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
if i==0:
result = node.val
return result
112. Path Sum
回溯
向下遍历时从target sum里减去此处的值,如果到叶子节点时计数为0,则返回true,
如果孩子返回true,父节点也返回true
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def hasPathSum(self, root, targetSum):
"""
:type root: TreeNode
:type targetSum: int
:rtype: bool
"""
if root == None:
return False
return self.traversal(root,targetSum - root.val)
def traversal(self, root, count):
if (root.left == None and root.right == None and count == 0):
return True
if (root.left == None and root.right == None and count != 0):
return False
if (root.left):
count -= root.left.val
if self.traversal(root.left,count):
return True
count += root.left.val #回溯向上
if (root.right):
count -= root.right.val
if self.traversal(root.right,count):
return True
count += root.right.val #回溯向上
return False
(略)106. Construct Binary Tree from Inorder and Postorder Traversal
略