513. Find Bottom Left Tree Value
Given a binary tree, find the leftmost value in the last row of the tree.
Example 1:
Input: 2 / \ 1 3 Output: 1
Example 2:
Input: 1 / \ 2 3 / / \ 4 5 6 / 7 Output: 7
给定一个二叉树,在树的最后一行找到最左边的值。
思路:可以使用层序遍历,然后取出最后一行的第一个元素即可
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
res=[]
if root is None:
return res
q=[root]
while len(q)!=0:
res.append([node.val for node in q])
new_q=[]
for node in q:
if node.left:
new_q.append(node.left)
if node.right:
new_q.append(node.right)
q=new_q
return res[-1][0]
515. Find Largest Value in Each Tree Row
You need to find the largest value in each row of a binary tree.
Example:
Input: 1 / \ 3 2 / \ \ 5 3 9 Output: [1, 3, 9]
您需要在二叉树的每一行中找到最大的值。
思路:还是使用层序遍历的思想
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res=[]
if root is None:
return res
q=[root]
while len(q)!=0:
res.append([node.val for node in q])
new_q=[]
for node in q:
if node.left:
new_q.append(node.left)
if node.right:
new_q.append(node.right)
q=new_q
rt=[]
for i in range(len(res)):
rt.append(max(res[i]))
return rt
530. Minimum Absolute Difference in BST
Given a binary search tree with non-negative values, find the minimum absolute differencebetween values of any two nodes.
Example:
Input: 1 \ 3 / 2 Output: 1 Explanation: The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
给定一个所有节点为非负值的二叉搜索树,求树中任意两节点的差的绝对值的最小值。
思路:中序遍历将BST中的节点按照递增顺序输出
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def getMinimumDifference(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
res=[]
def inOrder(root):
if root:
inOrder(root.left)
res.append(root.val)
inOrder(root.right)
inOrder(root)
minnum=min(res[i]-res[i-1] for i in range(1,len(res)))
return minnum