【剑指offer62 二叉搜索树的第k小节点】

题目描述

给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4。
 
 
先走到最小的节点,然后一步步往后退
直到计数为0 
/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    int count ;
    void inorder(TreeNode* root,TreeNode* &ans){
        if(root){
            inorder(root->left,ans);
            count--;  //会从最小的点开始--
            if(!count) ans = root;
            inorder(root->right,ans);
        }
    }
    
    TreeNode* KthNode(TreeNode* pRoot, int k)
    {
        if(!pRoot || k < 1) return nullptr;
        TreeNode* ans = NULL;
        count = k;
        inorder(pRoot,ans);
        return ans;
        
    }
};

 

posted @ 2020-06-15 20:50  Stephen~Jixing  阅读(132)  评论(0编辑  收藏  举报