[关闭]
@Lin-- 2020-02-17T12:13:35.000000Z 字数 586 阅读 315

trimBST

Leetcode


基础的剪枝算法,遇到结点值小于L时,返回右子树;遇到结点值大于R时,返回左子树。
否则一切照旧。最后返回结点。

  1. '''
  2. # File: trimBST.py
  3. # Author: 0HP
  4. # Date: 20200217
  5. # Purpose: solve the problem in website:
  6. # https://leetcode.com/problems/trim-a-binary-search-tree/
  7. '''
  8. # Definition for a binary tree node.
  9. class TreeNode:
  10. def __init__(self, x):
  11. self.val = x
  12. self.left = None
  13. self.right = None
  14. class Solution:
  15. def trimBST(self, root: TreeNode, L: int, R: int) -> TreeNode:
  16. if root==None:
  17. return None
  18. if root.val<L:
  19. return self.trimBST(root.right,L,R)
  20. elif root.val>R:
  21. return self.trimBST(root.left,L,R)
  22. else:
  23. root.left=self.trimBST(root.left,L,R)
  24. root.right=self.trimBST(roor.right,L,R)
  25. return root
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注