题解 | #二叉搜索树的第k个结点#
二叉搜索树的第k个结点
http://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a
知识点:对二叉搜索树进行中序遍历,可以得到一组升序数组。 解题思路:利用dfs中序递归二叉搜索树,输出数组中第k个结点。
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回对应节点TreeNode
def __init__(self):
self.count=0
def KthNode(self, pRoot, k):
# write code here
if not pRoot or not k:return None
res=[]
def in_order(cur):
if not cur: return
in_order(cur.left)
self.count+=1
res.append(cur)
in_order(cur.right)
in_order(pRoot)
if self.count<k:return None
return res[k-1]