剑指Offer对答如流系列

面试题54:二叉搜索树的第k个结点

题目描述

给定一棵二叉搜索树,请找出其中的第k小的结点。

例如,图中的二叉搜索树,按节点值大小顺序,第三大节点的值是4.
在这里插入图片描述

二叉搜索树的节点定义

	public class Node {
        int val = 0;
        Node left = null;
        Node right = null;

        public Node(int val) {
            this.val = val;
        }
    }

问题分析

二叉搜索树中序遍历的结果是顺序的。我们可以设置一个全局变量index,对二叉搜索树进行中序遍历时,每遍历一个结点,index++,当index=k时,该结点即为所求结点。

问题解答

	private int index=0;

    Node KthNode(Node pRoot, int k){
        Node pNode = null;
        if(pRoot==null || k<=0) {
            return pNode;
        }
        pNode = getKthNode(pRoot,k);
        return pNode;
    }

    private Node getKthNode(Node pRoot, int k){
        Node kthNode=null;

        if(pRoot.left!=null) {
            kthNode=getKthNode(pRoot.left,k);
        }
        
        if(kthNode==null){
            index++;
            if(k==index) {
                kthNode = pRoot;
            }
        }

        if(kthNode==null && pRoot.right!=null) {
            kthNode=getKthNode(pRoot.right,k);
        }
        
        return kthNode;
    }
原文地址:https://www.cnblogs.com/JefferyChenXiao/p/12246768.html