二叉树中第 K小的元素
给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。
说明:
你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。
思路: 二叉搜索树因其有序,故采用中序遍历,可以得到第K小的元素。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int kthSmallest(TreeNode* root, int k) { int index = k; int kth = 0; TreeNode* find = findKth(root, index, kth); if(find) return find->val; return -1; } TreeNode* findKth(TreeNode* root, int index, int &k){ if(root == NULL) { return NULL; } //左子树<根节点<右子树 TreeNode* left = findKth(root->left,index, k); if(left) return left; k = k+1; if(k == index){ // cout << root->val << ","; return root; } TreeNode* right = findKth(root->right, index, k); if(right) return right; else return NULL; //return right? right:left; } };
The Safest Way to Get what you Want is to Try and Deserve What you Want.