62. A k-node binary search tree (Python)

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.
 
Ideas: preorder
 1 class Solution:
 2     # 返回对应节点TreeNode
 3     def KthNode(self, pRoot, k):
 4         # write code here
 5         stack = []
 6         while stack or pRoot:
 7             if pRoot:
 8                 stack.append(pRoot)
 9                 pRoot = pRoot.left
10             else:
11                 pRoot=stack.pop()
12                 k-=1
13                 if k == 0:
14                     return pRoot
15                 pRoot=pRoot.right

2019-12-31 21:26:57

Guess you like

Origin www.cnblogs.com/NPC-assange/p/12127549.html