给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
1 # -*- coding:utf-8 -*- 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 class Solution: 8 def __init__(self): 9 self.l = [] 10 self.count = 0 11 12 def inOrder(self,root,k): 13 if root != None: 14 self.inOrder(root.left,k) 15 self.count += 1 16 if self.count == k: 17 self.l.append(root) 18 self.inOrder(root.right,k) 19 20 # 返回对应节点TreeNode 21 def KthNode(self, pRoot, k): 22 if k == 0: 23 return None 24 self.inOrder(pRoot,k) 25 if k > self.count: 26 return None 27 return self.l[0] 28 # write code here
Java版代码,leetcode地址:
1 class Solution { 2 List<Integer> list = new ArrayList<Integer>(); 3 4 public void inOrder(TreeNode node) { 5 if(node.left!=null) { 6 inOrder(node.left); 7 } 8 list.add(node.val); 9 if(node.right!=null) { 10 inOrder(node.right); 11 } 12 } 13 14 public int kthLargest(TreeNode root, int k) { 15 inOrder(root); 16 int[] array = list.stream().mapToInt(Integer::valueOf).toArray(); 17 int n = array.length; 18 return array[n-k]; 19 } 20 }