AcWing 70. 二叉搜索树的第k个结点
原题链接
简单
作者:
joyonline
,
2019-12-21 14:59:56
,
所有人可见
,
阅读 869
递归。满足条件跳出递归
class Solution {
public TreeNode kthNode(TreeNode root, int k) {
Solution s = new Solution();
List<TreeNode> list = new ArrayList();
return s.zx(root,k,list).get(k-1);
}
public List<TreeNode> zx(TreeNode root,int k,List<TreeNode> list){
if(root.left != null){
zx(root.left,k,list);
}
if(root != null){
list.add(root);
if(list.size() == k) {
new RuntimeException();
}
}
if(root.right != null){
zx(root.right,k,list);
}
return list;
}
}
非递归中序
class Solution {
public TreeNode kthNode(TreeNode root, int k) {
Stack<TreeNode> stack = new Stack();
stack.push(root);
int count = 0;
while(root!=null || !stack.isEmpty()){
while(root!=null){
stack.push(root);
root = root.left;
}
if(!stack.isEmpty()){
TreeNode t = stack.pop();//弹出根节点
count++;
if(count == k){
return t;
}
root = t.right;
}
}
return root;
}
}