Q-List
687. The value of the path with the longest
I think this question is very difficult wow, read the solution to a problem writing, personally feel that there are still many trick after ...... also we need to slowly goods
here "path" only two cases, the parent left or right, and no in the case of the parent node middle path, some say there are comments in this case, but to write a test case to see to know that in fact does not exist in this case.
class Solution(object):
def longestUnivaluePath(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.maxlength = 0
def isSame(node):
if not node: return 0
left_len = isSame(node.left)
right_len = isSame(node.right)
left = right = 0
if node.left and node.left.val == node.val:
left = left_len + 1
if node.right and node.right.val == node.val:
right = right_len + 1
self.maxlength = max(self.maxlength, left + right)
return max(left, right)
isSame(root)
return self.maxlength
783. binary search tree node the minimum distance
Results inorder traversal binary search tree is an array in ascending order, and then record the difference between the value of each node two pop out, to find the minimum value in the case of traversing the pass
class Solution(object):
def minDiffInBST(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.res = []
node = root
def saveTree(node):
while node:
self.res.append(node)
node = node.left
pre = -101
min_diff = 101
while node or self.res:
saveTree(node)
node = self.res.pop()
min_diff = min(min_diff, node.val - pre)
pre = node.val
node = node.right
return min_diff
Recursive wording
class Solution(object):
def minDiffInBST(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.pre = -101
self.min_diff = 101
def traverse(node):
if node:
traverse(node.left)
self.min_diff = min(self.min_diff, node.val - self.pre)
self.pre = node.val
traverse(node.right)
traverse(root)
return self.min_diff
938. The binary search tree scope and
Given the root of the binary search tree root, and values return all nodes L and R (inclusive).
Binary search tree has a unique value guarantee.
Example 1:
Input: root = [10,5,15,3,7, null, 18], L = 7, R = 15 Output: 32
Example 2:Input: root = [10,5,15,3,7,13,18,1, null, 6], L = 6, R = 10 Output: 23
prompt:
Number of nodes in the tree up to 10,000. The final answer to ensure that less than 2 ^ 31.
This problem is considered L <= node.val <= R and the line preorder
class Solution(object):
def rangeSumBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: int
"""
self.val = R + L
self.L = L
self.R = R
def tarverse(node):
if node:
tarverse(node.left)
if node.val > L and node.val < R:
self.val += node.val
# if node.val < L or node.val > R: return
tarverse(node.right)
tarverse(root)
return self.val