程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Sword finger offer python:52 The k-th node / k-th node of binary search tree

編輯:Python

subject : Given a binary search tree , Please find the first one K Big / The first k Small nodes .

Binary search tree : The value of the root node is greater than that of any node in its left subtree , Less than the value of any node in its right node , This rule applies to every node in the binary lookup tree .

Pictured :

  Ideas : Using the binary search tree feature , Stack .

Code :

# class root_tree:
# def f(self , root):
# self.root = root
# self.left = root.left
# self.right = root.right
class Solution:
def func_max(self , root , k):
stack = []
ans = root
while stack or root:
while root:
stack.append(root)
root = root.right
root = stack.pop()
k -= 1
ans = root
root = root.left
if k == 0:
return ans
def func_min(self , root , k):
stack = []
res = root
while stack or root:
while root:
stack.append(root)
root = root.left
root = stack.pop()
k -= 1
res = root
root = root.right
if k == 0:
return res


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved