题目描述
给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 24 6 8 中,按结点数值大小顺序第三个结点的值为4。
解法:
对于二叉搜索树而已,中序遍历就按照节点值从小到大遍历,因此进行中序遍历,第k个节点为所求。
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.Stack;
public class Solution {
TreeNode KthNode(TreeNode pRoot, int k){
if(pRoot==null || k==0){
return null;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode cur = pRoot;
int index = 0;
while(cur!=null || !stack.isEmpty()){
while(cur!=null){
stack.push(cur);
cur = cur.left;
}
TreeNode treeNode = stack.pop();
if(++index==k){
return treeNode;
}
if(treeNode!=null){
cur = treeNode.right;
}
}
return null;
}
}

本文介绍了一种寻找二叉搜索树中第K大结点的方法,通过中序遍历实现,确保找到的结点是按照数值大小顺序排列的第K个结点。

被折叠的 条评论
为什么被折叠?



