题目来源:
https://leetcode.com/problems/kth-smallest-element-in-a-bst/
自我感觉难度/真实难度:
题意:
分析:
自己的代码:
class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: self.res=0 self.k = k def inorder(node): global res if not node: return inorder(node.left) self.k-=1 if self.k==0: self.res=node.val return inorder(node.right) inorder(root) return self.res
代码效率/结果:
优秀代码:
def kthSmallest(self, root, k): self.k = k self.res = None self.helper(root) return self.res def helper(self, node): if not node: return self.helper(node.left) self.k -= 1 if self.k == 0: self.res = node.val return self.helper(node.right)
def kthSmallest(root, k): stack = [] while root or stack: while root: stack.append(root) root = root.left root = stack.pop() k -= 1 if k == 0: return root.val root = root.right
https://leetcode.com/problems/kth-smallest-element-in-a-bst/discuss/63829/Python-Easy-Iterative-and-Recursive-Solution
代码效率/结果:
自己优化后的代码:
反思改进策略:
1.读题要仔细,认真看懂题目再写
2.如何用递归、循环从小到大遍历一个搜索树
3.函数的输入参数,只能在自己函数范围内使用
函数内部在定义函数,可以使用 self.k=k,使得整个solution类都可以使用self.k