题目:给定一颗二叉搜索树,请找出其中第K大的节点。
核心思想:中序遍历
如上图,中序遍历的结果位:2,3,4,5,6,7,8,则在该二叉搜索树中第3大的节点值为4.
具体代码如下:
public class Solution {
int index = 0;
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot == null || k < 0) return null;
TreeNode KthNode = null;
KthNode = getKthNode(pRoot, k);
return KthNode;
}
public TreeNode getKthNode(TreeNode root, int k)
{
TreeNode KthNode = null;
if(root.left != null)
{
KthNode = getKthNode(root.left, k);
}
if(KthNode == null)
{
index++;
if(index == k)
{
KthNode = root;
}
}
if(KthNode == null && root.right != null)
{
KthNode = getKthNode(root.right, k);
}
return KthNode;
}
}
``
第二种写法:注意:二叉搜索树的中序遍历是递增序列
public class Solution
{
int index = 0;
int kthValue ;
public int getKthNode(TreeNode root, int k)
{
if(root == null) return 0;
inOrder(root,k);
}
public void inOrder(TreeNode root, int k)
{
if(root == null)
return;
inOrder(root.left,k);
if(index == k)
return;
index++;
kthValue = root.val;
inOrder(root.right, k);
}
}