## Title Description

Given a binary search tree, please find the first k smaller nodes therein. For example, (5,3,7,2,4,6,8), the numerical values ​​according to the third junction point is 4 summary.

## Thinking

In fact, the traversal sequence, the k-th node traversed

``````# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
def KthNode(self, root, k):
#相当于中序遍历，遍历到的第k个点
if k<=0 or not root:
return None

index = 0
nodes = []
while 1:
while 1:
while root.left:
nodes.append(root)
root = root.left
index += 1
if index == k:
return root
if root.right:
root = root.right
else:
break
if len(nodes)>0:
root = nodes.pop()
index += 1
if index == k:
return root
while root.right == None and len(nodes)>0:
root = nodes.pop()
index += 1
if index == k:
return root
if root.right:
root = root.right
else:
break
else:
break
return None``````

Published 82 original articles · won praise 2 · Views 4344

### Guess you like

Origin blog.csdn.net/qq_22498427/article/details/104983098
Recommended
Ranking
Daily