leetcode 230. Kth Smallest Element in a BST
https://www.cnblogs.com/grandyang/p/4620012.html
这个题其实就是中序遍历第k个数就好了,代码最好写的就是非递归的方式,在stack里面找第k个就好了。也可以使用递归的方式:
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。class Solution { public: int kthSmallest(TreeNode* root, int k) { return Smallest(root,k); } int Smallest(TreeNode* root,int& k){ if(root == NULL) return -1; int num = Smallest(root->left,k); if(k == 0) return num; if(--k == 0) return root->val; return Smallest(root->right,k); } };
注意:这种递归的方法在NULL时候返回-1,如果找到了数字,返回值就会以当前的结果替代-1.

更多精彩