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); } } }