剑指offer-----二叉搜索树的第k大节点

1、题目描述

给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。

2、思想

中序遍历该二叉搜索树,很容易找出它的第k大节点。

3、代码

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;


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


    }


}
*/
public class Solution {
    int k = 0;//必须将k定义为成员属性,而不能作为参数传递,作为参数传递的话,参数在里层函数中的
              //的变化,外层函数不会知道
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        if(pRoot==null || k<=0){
            return null;
        }
        this.k = k;
        return kthNodeCore(pRoot);
        
    }
    TreeNode kthNodeCore(TreeNode pRoot){
        TreeNode target = null;
        if(pRoot.left != null){
            target = kthNodeCore(pRoot.left);
        }
        if(target == null){
            if(k == 1){
                target = pRoot;
            }
            k--;
            
           
        }
        if(target==null && pRoot.right!=null){
            target = kthNodeCore(pRoot.right);
        }
        return target;
    }

}

猜你喜欢

转载自blog.csdn.net/g1607058603/article/details/80911013