• 递归与二叉树_leetcode230


    # Definition for a binary tree node.
    class TreeNode(object):
    def __init__(self, x):
    self.val = x
    self.left = None
    self.right = None


    # 即中序遍历的第K个节点
    class Solution1(object):
    def kthSmallest(self, root, k):
    self.count=k
    self.res=0

    def core(root):
    if root :

    core(root.left)

    self.count=self.count-1
    if self.count==0:
    self.res=root.val

    core(root.right)

    core(root)
    return self.res



    # 这个栈的中序遍历好不规范呀
    class Solution2(object):
    def kthSmallest(self, root, k):
    stack=[]
    while True:
    if root:
    stack.append(root)
    root=root.left
    else:
    root=stack.pop()
    k=k-1
    if k==0:
    return root.val
    else:
    root=root.right



    class Solution3(object):
    def kthSmallest(self, root, k):

    res = []
    self.midOrder(root,res)
    return res[k-1]



    def midOrder(self,root,res):

    if not root:
    return


    self.midOrder(root.left,res)
    res.append(root.val)
    self.midOrder(root.right,res)

    return res




    # 启示: 下层的K值无法改变上层的k值,所以要用全局变量
    class Solution4(object):
    def kthSmallest(self, root, k):


    return self.midOrder(root,k)


    def midOrder(self,root,k):

    if not root:
    return

    self.midOrder(root.left,k)

    k = k-1
    if k == 0:
    return root.val

    self.midOrder(root.right,k)


    def createTreee(self):
    root = TreeNode(3)
    root.left = TreeNode(1)
    root.right = TreeNode(4)
    root.left.right = TreeNode(2)

    return root


    class Solution5(object):
    def kthSmallest(self, root, k):
    self.count = 0
    self.res = 0

    self.midOrder(root,k)

    return self.res


    def midOrder(self,root,k):

    if not root:
    return


    self.midOrder(root.left,k)

    self.count += 1
    if k == self.count:
    self.res = root.val
    return

    self.midOrder(root.right,k)



    class Solution6(object):
    def kthSmallest(self, root, k):
    if not root:
    return root

    count = k
    stack = []

    stack.append(root.left)




    s = Solution4()

    root = s.createTreee()

    s.kthSmallest(root,1)





  • 相关阅读:
    Codeforces 377 A Maze【DFS】
    分糖果 5.0升级版
    poj_1201_Intervals
    NOIP2016全国信息学分区联赛提高组第二试 组合问题
    NOIP2016全国信息学分区联赛提高组第一试 玩具迷题
    NOIP 2016提高组总结
    2016年提高组模拟试题(20161105)Mahjong
    打鼹鼠
    2015年普级组模拟试题 小X的矩阵
    交汇的火力
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10546795.html
Copyright © 2020-2023  润新知