美文网首页
二叉搜索树的第k个结点

二叉搜索树的第k个结点

作者: Crazy_Bear | 来源:发表于2020-07-24 10:52 被阅读0次
  • 给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
  • 中序遍历即可
  • C++ 可以通过指针直接获取结果值,Java还是老老实实使用返回值吧
  • Java代码
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    int index = 0;
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        if(pRoot!=null) {
            TreeNode node =  KthNode(pRoot.left, k);
            if(node != null) return node;
            index++;
            if(index == k) return pRoot;
            node = KthNode(pRoot.right, k);
            if(node != null) return node;
        }
        return null;
    }
}
  • C++ 代码
/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    TreeNode* KthNode(TreeNode* pRoot, int k)
    {
        if(!pRoot && k ==0) return nullptr;
        int count = 0;
        TreeNode * res = 0;
        inorder(pRoot, k ,count, res);
        return res;
    }
    void inorder(TreeNode *pRoot, int k , int &count, TreeNode* &res){
        if(pRoot==nullptr) return ;
        dfs(pRoot->left,k,  count,res);
        count += 1;
        if(count == k) res = pRoot;
        dfs(pRoot->right, k, count, res);
    }
};

相关文章

网友评论

      本文标题:二叉搜索树的第k个结点

      本文链接:https://www.haomeiwen.com/subject/jlcjlktx.html