Uriel's Corner

Research Associate @ Harvard University / Research Interests: Computer Vision, Biomedical Image Analysis, Machine Learning
posts - 0, comments - 50, trackbacks - 0, articles - 594
给出一颗二叉搜索树,求树中数值范围处于[low, high]的节点之和,DFS,如果当前节点处于[low, high],则左右子树都要搜索,如果当前节点小于low,只需要搜索右子树,如果当前节点大于high,只需要搜索左子树,不过这题数据比较简单,直接深搜完整棵树,遇到处于[low, high]的节点就累加也可以过

只搜索特定子树:

 1 #938
 2 #Runtime: 284 ms
 3 #Memory: 29.9 MB
 4 
 5 # Definition for a binary tree node.
 6 # class TreeNode(object):
 7 #     def __init__(self, val=0, left=None, right=None):
 8 #         self.val = val
 9 #         self.left = left
10 #         self.right = right
11 class Solution(object):
12     def rangeSumBST(self, root, low, high):
13         """
14         :type root: TreeNode
15         :type low: int
16         :type high: int
17         :rtype: int
18         """
19         def DFS(r):
20             if not r:
21                 return 0
22             if r.val >= low and r.val <= high:
23                 return r.val + DFS(r.left) + DFS(r.right)
24             if r.val < low:
25                 return DFS(r.right)
26             if r.val > high:
27                 return DFS(r.left)
28         return DFS(root)

暴力搜完整棵树:

 1 #938
 2 #Runtime: 535 ms
 3 #Memory: 29.5 MB
 4 
 5 # Definition for a binary tree node.
 6 # class TreeNode(object):
 7 #     def __init__(self, val=0, left=None, right=None):
 8 #         self.val = val
 9 #         self.left = left
10 #         self.right = right
11 class Solution(object):
12     def rangeSumBST(self, root, low, high):
13         """
14         :type root: TreeNode
15         :type low: int
16         :type high: int
17         :rtype: int
18         """
19         self.ans = 0
20         def DFS(r):
21             if not r:
22                 return
23             DFS(r.left)
24             if r.val >= low and r.val <= high:
25                 self.ans += r.val
26             DFS(r.right)
27         DFS(root)
28         return self.ans

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理