标签:
Given a binary search tree, write a function kthSmallest
to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST‘s total elements.
题意:
给定一个二分搜索树,返回第K小的结点
思路:
只要明白BST树的原理,只要中序遍历一遍BST树即可。求第K小的,只需遍历前K个结点就OK。
C++:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 13 int ret, cnt, _k; 14 15 void rec(TreeNode *root) 16 { 17 if(root->left == 0 && root->right == 0) 18 { 19 cnt++; 20 if(cnt == _k) 21 ret = root->val; 22 return ; 23 } 24 25 if(root->left != 0) 26 rec(root->left); 27 28 cnt++; 29 if(cnt == _k){ 30 ret = root->val; 31 return ; 32 } 33 34 if(root->right != 0) 35 rec(root->right); 36 } 37 38 int kthSmallest(TreeNode* root, int k) { 39 if(root == 0) 40 return 0; 41 42 _k = k; cnt = ret = 0; 43 44 rec(root); 45 46 return ret; 47 } 48 };
Python:
1 # Definition for a binary tree node. 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution: 9 # @param {TreeNode} root 10 # @param {integer} k 11 # @return {integer} 12 13 def __init__(self): 14 self.cnt = 0 15 self.ret = 0 16 17 def rec(self, root, k): 18 if root.left is None and root.right is None: 19 self.cnt = self.cnt + 1 20 if self.cnt == k: 21 self.ret = root.val 22 return 23 24 if root.left is not None: 25 self.rec(root.left, k) 26 27 self.cnt = self.cnt + 1 28 if self.cnt == k: 29 self.ret = root.val 30 return 31 32 if root.right is not None: 33 self.rec(root.right, k) 34 35 def kthSmallest(self, root, k): 36 if root is None: 37 return 0 38 39 self.rec(root, k) 40 41 return self.ret
【LeetCode 230】Kth Smallest Element in a BST
标签:
原文地址:http://www.cnblogs.com/tjuloading/p/4617161.html