230. 二叉搜索树中第K小的元素
230. 二叉搜索树中第K小的元素
https://leetcode.cn/problems/kth-smallest-element-in-a-bst/
思路
https://leetcode.cn/problems/kth-smallest-element-in-a-bst/solutions/1050055/er-cha-sou-suo-shu-zhong-di-kxiao-de-yua-8o07/
根据二叉搜索树性质,
对左子树进行搜索目标, 根节点判断, 然后对右子树进行目标搜索。
https://zhuanlan.zhihu.com/p/29867652
Code
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { int count = 0; public: int kthSmallest(TreeNode* root, int k) { return inorder(root, k); } private: /* return kth value if found in this root, otherwise -1 */ int inorder(TreeNode* root, int k){ if (root->left){ int leftret = inorder(root->left, k); if (leftret != -1){ return leftret; } } count++; if (count == k){ return root->val; } if (root->right){ int rightret = inorder(root->right, k); if (rightret != -1){ return rightret; } } return -1; } };
出处:http://www.cnblogs.com/lightsong/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。