230. 搜索二叉树中第K小的值

用dfs解
搜索二叉树的中序遍历是从小到大的顺序。

    def KthNode(self, pRoot, k):
        if not pRoot:
            return None
        # 用dfs解,中序遍历
        stack = []
        while True:
            # 中序遍历,先处理左孩子,再处理右孩子
            while pRoot:
                # root不为空压入堆栈中
                stack.append(pRoot)
                pRoot = pRoot.left
            try:
                cur = stack.pop()
            except:
                # 如果k大于树的结点数量
                return None
            k -= 1
            if k == 0:
                return cur
            pRoot = cur.right

你可能感兴趣的:(230. 搜索二叉树中第K小的值)