AcWing 70. 二叉搜索树的第k个结点-Java
原题链接
简单
作者:
Shanzhihong
,
2019-07-25 09:47:48
,
所有人可见
,
阅读 1582
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private TreeNode ans = new TreeNode(-1);
private int a = 0;//值调用的问题,所以要定义全局变量
public TreeNode kthNode(TreeNode root, int k) {
a = k;
dfs(root);
return ans;
}
public void dfs(TreeNode root){
if(root == null) return;
dfs(root.left);
if(--a == 0) ans = root;
dfs(root.right);
}
}