题解 | #二叉搜索树的第k个节点#

二叉搜索树的第k个节点

http://www.nowcoder.com/practice/57aa0bab91884a10b5136ca2c087f8ff

#coding:utf-8
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#

# @param proot TreeNode类 
# @param k int整型 
# @return int整型
#
class Solution:
    def __init__(self):
        self.count = 0
    
    def KthNode(self , proot , k ):
        # write code here
        stack = []
        if k <=0:
            return -1
        cur = proot
        if not cur:
            return -1
        while cur or len(stack)>0:
            while cur:
                stack.append(cur)
                cur = cur.left
            while len(stack)>0:
                ret = stack.pop()
                self.count += 1
                print(ret.val)
                if self.count == k:
                    return ret.val
                
                if ret.right is not None:
                    cur = ret.right
#                     print(":",cur.val)
                    break
                else:
                    continue
        return -1
                                
        
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务