题解 | #二叉搜索树的第k个结点#
二叉搜索树的第k个结点
http://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a
二叉搜索树特性:
左孩子 < 根节点 < 右孩子
可以利用二叉树的中序遍历得到答案
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
TreeNode KthNode(TreeNode pRoot, int k) {
if (pRoot == null || k < 1) {
return null;
}
List<TreeNode> list = new ArrayList<>();
treeDeep (pRoot, list);
if (list.size() < k) {
return null;
}
return list.get(k-1);
}
public void treeDeep (TreeNode pRoot, List<TreeNode> list) {
if (pRoot == null) {
return;
}
treeDeep(pRoot.left, list);
list.add(pRoot);
treeDeep(pRoot.right, list);
}
}刷刷题 文章被收录于专栏
刷刷题 活跃活跃脑细胞
查看22道真题和解析