面試題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;
}