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/ 根据二叉搜索树性质, 对左子树进行搜索目标, 根节点判断, 然后对右子树进行目标搜索。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; } };
标签:right,TreeNode,int,树中,二叉,return,root,230,left From: https://www.cnblogs.com/lightsong/p/18063844