62.二叉搜索樹的第k個結點

題目描述

給定一棵二叉搜索樹,請找出其中的第k小的結點。例如, (5,3,7,2,4,6,8)    中,按結點數值大小順序第三小結點的值爲4。

題目解答

 

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

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

    }

}
*/
public class Solution {
    int count=0;
    TreeNode KthNode(TreeNode pRoot, int k) {
        //遞歸終止條件
        if(pRoot==null){
            return null;
        }
        
        //左子樹中找符合要求的節點
        TreeNode node=KthNode(pRoot.left,k);
        if(node!=null) return node;
        
        //
        if(++count==k) return pRoot;

        //右子樹中找符合要求的節點
        node=KthNode(pRoot.right,k);
        if(node!=null) return node;
        
        return null;
    }
}
二叉搜索樹按照中序遍歷的順序打印出來正好就是排序好的順序。
按照中序遍歷順序找到第k個結點便可。
相關文章
相關標籤/搜索