剑指62.二叉搜索树的第k个结点

题目描述

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

思路

如果中序遍历一棵二叉搜索树,则遍历序列的数值是递增排序的。因此,只需要在中序遍历节点的过程中,判断当前遍历的节点是否为第k个节点就行了

 

解法

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

    public TreeNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {
    private int index = 1;
    private TreeNode ans = null;
    TreeNode KthNode(TreeNode pRoot, int k) {
        if (pRoot == null || k <= 0)
            return null;
        getKthNode(pRoot,k);
        return ans;
    }
    // 找第k小的节点
    private void getKthNode(TreeNode node, int k){
        if (ans == null){ // 剪枝操作,ans为空时说明还没找到第k个节点,如果找到了就没必要遍历其他节点了
            if (node.left != null)
                getKthNode(node.left,k);
            if (index == k){
                ans = node;
            }
            index++;
            if (node.right != null)
                getKthNode(node.right,k);
        }
    }
    
    // 举一反三:找第k大的节点
    // 思路:只需要更改中序遍历的遍历方式,改为 右→根→左。 这样遍历的序列就是递减排序的
    /*private void getKthNode(TreeNode node, int k){
        if (ans == null){ // 剪枝操作,ans为空时说明还没找到第k个节点,如果找到了就没必要遍历其他节点了
            if (node.right != null)
                getKthNode(node.right,k);
            if (index == k){
                ans = node;
            }
            index++;
            if (node.left != null)
                getKthNode(node.left,k);
        }
    }*/
}

 

 
posted @ 2020-09-09 15:00  不学无墅_NKer  阅读(137)  评论(0编辑  收藏  举报