/*
* 给定一颗二叉搜索树,请找出其中的第k大的结点。
* 如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
* 思路:本题实际上就是一个二叉搜索树的中序遍历,是因为二叉搜索树的中序遍历是一个递增序列
*/
public class FindKthNode {
//非递归中序遍历
public TreeNode kthNode(TreeNode pRoot, int k) {
if(pRoot == null || k <= 0) return null;
Stack<TreeNode> stack = new Stack<TreeNode>();
int count = 0;
TreeNode kthNode = null;
while(!stack.isEmpty() || pRoot != null) {
while(pRoot != null) {
stack.push(pRoot);
pRoot = pRoot.left;
}
TreeNode node = stack.pop();
count ++;
if(count == k) {
kthNode = node;
//System.out.println("我跳出循环了" + kthNode.val);
break;
}
pRoot = node.right;
}
return kthNode;
}
//递归中序遍历
public TreeNode kthNode2(TreeNode pRoot, int k) {
if(pRoot == null || k <= 0) return null;
ArrayList<TreeNode> list = new ArrayList<TreeNode>();
middleOrder(pRoot, list);
if(k > list.size())
return null;
return list.get(k - 1);
}
public void middleOrder(TreeNode pRoot, ArrayList<TreeNode> list) {
if(pRoot == null) return;
if(pRoot.left == null && pRoot.right == null) {
list.add(pRoot);
return;
}
middleOrder(pRoot.left, list);
list.add(pRoot);
middleOrder(pRoot.right, list);
return;
}
public static void main(String[] args) {
TreeNode root1 = new TreeNode(5);
root1.left = new TreeNode(3);
root1.right = new TreeNode(7);
root1.left.left = new TreeNode(2);
root1.left.right = new TreeNode(4);
root1.right.left = new TreeNode(6);
root1.right.right = new TreeNode(8);
System.out.println(new FindKthNode().kthNode2(root1, 5).val);
}
}
《剑指offer》-寻找二叉搜索树第k大的结点
最新推荐文章于 2020-12-16 14:42:46 发布