二叉搜索树的第k个结点

题目描述

给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
此树按照中序遍历打出来是[2 3 4 5 6 7 8],所以第三大的节点是4
Solution 1://借助stack
public class Solution {
int count = 0;
TreeNode KthNode(TreeNode pRoot, int k) {
if(count > k || pRoot == null)
return null;
TreeNode p = pRoot;
Stack<TreeNode> stack = new Stack<>();
TreeNode kthNode = null;
stack.push(pRoot);
while(!stack.isEmpty()){
TreeNode tn = stack.peek();
while(tn != null){
tn = tn.left;
stack.push(tn);
}
stack.pop();
if (!stack.isEmpty()) {
tn = stack.pop();
count++;
if (count == k)
kthNode = tn;
stack.push(tn.right);
}
}
return kthNode;
}
Solution 2:
public class Solution {
int k;
TreeNode temp = null;
public TreeNode KthNode(TreeNode pRoot, int k) {
this.k = k;
helper(pRoot);
return temp;
}

public void helper(TreeNode pRoot) {
if (pRoot == null)
return;
helper(pRoot.left);
if (--k == 0)
temp = pRoot;
helper(pRoot.right);
}
}
posted @ 2018-10-11 16:57  MarkLeeBYR  阅读(393)  评论(0编辑  收藏  举报