题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。
示例1:
输入:
{5,3,7,2,4,6,8},3返回值:{4}
说明: 按结点数值大小顺序第三小结点的值为4
知识点
1)二叉搜索树的中序遍历,找第k个
代码
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # 返回对应节点TreeNode def KthNode(self, pRoot, k): # write code here重点是写出中序遍历,左子树-根节点-右子树 a=[] a=self.in_search(pRoot,a) if k<=0 or k>len(a): return None return a[k-1] def in_search(self,tree,a): if tree: self.in_search(tree.left,a) a.append(tree) self.in_search(tree.right,a) return a
这里以下写法会报错:'NoneType' object has no attribute 'append',不知道什么原因
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # 返回对应节点TreeNode def KthNode(self, pRoot, k): # write code here重点是写出中序遍历,左子树-根节点-右子树 a=[] a=self.in_search(pRoot,a) if k<=0 or k>len(a): return None return a[k-1] def in_search(self,tree,a): if tree.left: self.in_search(tree.left,a) a.append(tree) if tree.right: self.in_search(tree.right,a) return a