/** * 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 k_time; int temp; void kth_min(TreeNode* root) { if(root->left!=NULL)//不停找左节点 kth_min(root->left); if(k_time>0)//查看k减少到0没 k_time--; else return; if(k_time==0)//如果为0,把当前节点赋给temp temp=root->val; if(root->right!=NULL) kth_min(root->right); } int kthSmallest(TreeNode* root, int k) { k_time=k; kth_min(root); return temp; } };
分析:
中序进行一半,找到k值就返回。
原文地址:https://www.cnblogs.com/CJT-blog/p/10722640.html
时间: 2024-10-08 07:55:10