代码改变世界

230_Kth Smallest Element in a BST

2016-03-21 19:32  FTD_W  阅读(140)  评论(0编辑  收藏  举报

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note: 
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

 

给定一个二叉搜索树,找出第K小的节点

 

左节点 < 中间节点 < 右节点            用一个数组按顺序从小到大保存所有节点的值,第K小就是下标K-1的数字

中序遍历记录节点的值即可

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