题解 | 二叉搜索树的第k个结点
二叉搜索树的第k个结点
https://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a?tpId=13&&tqId=11215&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
树结构:
/* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */
二叉搜索树的中序序列是升序序列:
import java.util.*; public class Solution { public TreeNode KthNode(TreeNode root, int k) { List<TreeNode> l = new ArrayList<>(); inOrder(root, l); if (k > l.size() || k < 1) return null; else return l.get(k-1); } // 递归辅助函数 private void inOrder(TreeNode root, List<TreeNode> list) { if (root != null) { inOrder(root.left, list); list.add(root); inOrder(root.right, list); } } }