Given a binary search tree, write a function kthSmallest
to find the kth smallest element in it.node
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.数组
给定一个二叉搜索树,找出第K小的节点spa
左节点 < 中间节点 < 右节点 用一个数组按顺序从小到大保存全部节点的值,第K小就是下标K-1的数字code
中序遍历记录节点的值便可blog
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */ public class Solution { private List<int> sortedArray = new List<int>(); public int KthSmallest(TreeNode root, int k) { if(root == null) { return 0; } sortSearch(root); return sortedArray[k - 1]; } public void sortSearch(TreeNode root) { if(root.left != null) { sortSearch(root.left); } sortedArray.Add(root.val); if(root.right != null) { sortSearch(root.right); } } }