dfs O(n)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
class Solution { public: int kthSmallest(TreeNode* root, int k) { int res = 0; dfs(root, k, res); return res; }
void dfs(TreeNode *root, int &k, int &res) { if (!root) return; dfs(root->left, k, res); if (--k == 0) { res = root->val; return; } dfs(root->right, k, res); } };
|
follow up 给每个节点加一个count来记录当前节点这棵树的所有节点的个数,初始化为1,即只有根节点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
class Solution { public: int kthSmallest(TreeNode* root, int k) { TreeNodeWithCount *node = buildTree(root); return kthSmallest(node, k); }
private: struct TreeNodeWithCount { int val; int count; TreeNodeWithCount *left; TreeNodeWithCount *right; TreeNodeWithCount(int x) : val(x), count(1), left(nullptr), right(nullptr) {} };
TreeNodeWithCount * buildTree(TreeNode *root) { if (!root) return nullptr; TreeNodeWithCount *node = new TreeNodeWithCount(root->val); node->left = buildTree(root->left); node->right = buildTree(root->right); if (node->left) node->count += node->left->count; if (node->right) node->count += node->right->count; return node; }
int kthSmallest(TreeNodeWithCount *root, int k) { if (root->left) { if (root->left->count >= k) return kthSmallest(root->left, k); if (root->left->count == k - 1) return root->val; return kthSmallest(root->right, k - 1 - root->left->count); } else { if (k == 1) return root->val; return kthSmallest(root->right, k - 1); } } };
|