zoukankan      html  css  js  c++  java
  • 62.二叉搜索树的第k个节点(python)

    题目描述

    给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4。
     
    思路:中序遍历
     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

     1 class Solution:
     2     # 返回对应节点TreeNode
     3     def KthNode(self, pRoot, k):
     4         # write code here
     5         def preorder(pRoot):
     6             if pRoot == None:
     7                 return []
     8             return preorder(pRoot.left)+[pRoot]+preorder(pRoot.right)
     9         res = preorder(pRoot)
    10         if len(res)<k or k < 1:
    11             return None
    12         return res[k-1]

    递归版

     1 class Solution:
     2     # 返回对应节点TreeNode
     3     def __init__(self):
     4         self.count=0
     5     def KthNode(self, pRoot, k):
     6         # write code here
     7         if pRoot == None:
     8             return None
     9         node = self.KthNode(pRoot.left,k)
    10         if node:
    11             return node
    12         self.count += 1
    13         if self.count == k:
    14             return pRoot
    15         node = self.KthNode(pRoot.right,k)
    16         if node:
    17             return node
  • 相关阅读:
    maven的安装教程
    webstorm的中文教程和技巧分享
    WebStorm
    grunt配置任务
    grunt快速入门
    CSS简介
    浅介HTML DOM
    【转】计算机是如何启动的?
    【转】深入理解C++中public、protected及private用法
    【转】VS2013动态库文件的创建及其使用详解
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/12127549.html
Copyright © 2011-2022 走看看