迭代法:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def kthSmallest(self, root: TreeNode, k: int):
def in_stack(node, stack):
while node:
stack.append(node)
node = node.left
return stack
stack = []
result = []
stack = in_stack(root, stack)
while stack:
node = stack.pop()
result.append(node.val)
k = k-1
if k==0:
return result[-1]
if node.right:
stack = in_stack(node.right, stack)
迭代法:简洁的代码
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def kthSmallest(self, root: TreeNode, k: int):
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