其他分享
首页 > 其他分享> > 剑指Offer62:二叉搜索树的第k个结点

剑指Offer62:二叉搜索树的第k个结点

作者:互联网

题目:给定一棵节点数为 n 二叉搜索树,请找出其中的第 k 小的TreeNode结点。

解法:用中序遍历,遍历的第n的个节点就是第k小的。

public class Solution {
    private TreeNode result;
    private int count;
    TreeNode KthNode(TreeNode pRoot, int k) {
        if(pRoot == null || k == 0)
            return null;
        getKMin(pRoot,k);
        return result;
    }
    
    
    void getKMin(TreeNode pRoot, int k){
        if(pRoot == null || count >= k)
            return;
        getKMin(pRoot.left,k);
        count ++;
        if (count == k)
            result = pRoot;
        getKMin(pRoot.right,k);
    }
}

标签:count,结点,TreeNode,Offer62,int,getKMin,pRoot,二叉,result
来源: https://blog.csdn.net/wangwangnvzi/article/details/120603389