方法一:递归(逆序的先序遍历)
思路:查找第K小的结点。二叉搜索树按照中序遍历就是从小到大的顺序排列,所以直接套用中序遍历的思想,递归即可。(力扣上是第K大的结点,同理,只要先遍历root.right后遍历root.left即可。
int count=0;
int res=0;
public int kthLargest(TreeNode root, int k){
this.count=k;
dfs(root);
return res;
}
public void dfs(TreeNode root){
if(root==null) return;
dfs(root.right);
if(--count==0){
res=root.val;
return;
}
dfs(root.left);
}
方法二:迭代
public int kthLargest(TreeNode root, int k){
Stack<TreeNode> stack=new Stack<>();
TreeNode node=root;
int count=1;
while(!stack.isEmpty()||node!=null){
while(node!=null){
stack.push(node);
node=node.right;
}
if(!stack.isEmpty()){
node=stack.pop();
if(count==k) return node.val;
count++;
node=node.left;
}
}
return 0;
}