深度优先搜索
- 思路:
- 二叉搜索树的特性,通过中序遍历得到有序序列,则遍历到第K个节点的时候即为结果;
- 使用栈通过深度优先遍历进行中序遍历:
- 先将节点和左子节点压栈;
- 然后栈顶上就是“最左”叶子节点;
- 然后通过栈回溯其父节点 p ,将 p 右子树压栈,重复上述过程;
/*** 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 {
public:int kthSmallest(TreeNode* root, int k) {std::stack<TreeNode*> stack;TreeNode* node = root;while (node != nullptr || stack.size() > 0) {while (node != nullptr) {stack.push(node);node = node->left;}node = stack.top();stack.pop();--k;if (k == 0) {break;}node = node->right;}return node->val;}
};