# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 即中序遍历的第K个节点
class Solution1(object):
def kthSmallest(self, root, k):
self.count=k
self.res=0
def core(root):
if root :
core(root.left)
self.count=self.count-1
if self.count==0:
self.res=root.val
core(root.right)
core(root)
return self.res
# 这个栈的中序遍历好不规范呀
class Solution2(object):
def kthSmallest(self, root, k):
stack=[]
while True:
if root:
stack.append(root)
root=root.left
else:
root=stack.pop()
k=k-1
if k==0:
return root.val
else:
root=root.right
class Solution3(object):
def kthSmallest(self, root, k):
res = []
self.midOrder(root,res)
return res[k-1]
def midOrder(self,root,res):
if not root:
return
self.midOrder(root.left,res)
res.append(root.val)
self.midOrder(root.right,res)
return res
# 启示: 下层的K值无法改变上层的k值,所以要用全局变量
class Solution4(object):
def kthSmallest(self, root, k):
return self.midOrder(root,k)
def midOrder(self,root,k):
if not root:
return
self.midOrder(root.left,k)
k = k-1
if k == 0:
return root.val
self.midOrder(root.right,k)
def createTreee(self):
root = TreeNode(3)
root.left = TreeNode(1)
root.right = TreeNode(4)
root.left.right = TreeNode(2)
return root
class Solution5(object):
def kthSmallest(self, root, k):
self.count = 0
self.res = 0
self.midOrder(root,k)
return self.res
def midOrder(self,root,k):
if not root:
return
self.midOrder(root.left,k)
self.count += 1
if k == self.count:
self.res = root.val
return
self.midOrder(root.right,k)
class Solution6(object):
def kthSmallest(self, root, k):
if not root:
return root
count = k
stack = []
stack.append(root.left)
s = Solution4()
root = s.createTreee()
s.kthSmallest(root,1)