题目
给定一颗二叉搜索树,请找出其中的第k大的结点。例如
按结点数值大小顺序第三个结点的值为4。
思路
利用二叉搜索数中序遍历有序的特点,用递归和迭代分别实现中序遍历。
package com.zhumq.leetcode;
import java.util.Stack;
public class KthNode {
public class TreeNode{
TreeNode left;
TreeNode right;
int val;
public TreeNode(int val){
this.val = val;
}
}
/**
* 解法1:非递归的中序遍历,每次出栈时令计数count++,当count==k,返回弹出的节点即可
*/
public TreeNode kthNode1(TreeNode pRoot,int k) {
if(pRoot == null|| k==0) return null;
int count = 0;
Stack<TreeNode> stack = new Stack<>();
while(!stack.isEmpty()) {
//遍历最左下节点
while(pRoot != null) {
stack.push(pRoot);
pRoot = pRoot.left;
}
//到左下后出栈
pRoot = stack.pop();
count++;
if(count == k) return pRoot;
pRoot = pRoot.right;
}
return null;
}
/**
* 解法2:递归的中序遍历
*/
//定义成员变量result和count
private TreeNode result;
private int count;
public TreeNode kthNode2(TreeNode pRoot,int k) {
inorder(pRoot,k);
return result;
}
private void inorder(TreeNode pRoot, int k) {
//一个方法调用另一个方法,里面方法要使用外面方法的参数时需要通过参数传进来不能直接使用!
if(pRoot == null) return;
if(count > k) return;
//左根右,先遍历左子树,左子树遍历结束当前节点再count++
inorder(pRoot.left,k);
count++;
//最后遍历右子树
inorder(pRoot.right,k);
}
}