【LeetCode】Kth Smallest Element in a BST 解题报告

来源:互联网 发布:lte中mr优化案例 编辑:程序博客网 时间:2024/06/05 15:29

【LeetCode】Kth Smallest Element in a BST 解题报告

标签(空格分隔): LeetCode


题目地址:https://leetcode.com/problems/kth-smallest-element-in-a-bst/#/description

题目描述:

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.

Ways

这个题比较简单,提到BST就应该想到它的中序遍历是有序的,因此,我的第一想法就是获取中序遍历的list,直接得到第k个数即可。方法很简单,注意中序遍历的写法,以及,获取第k个数的List标号是k-1.

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    List<Integer> list;    public int kthSmallest(TreeNode root, int k) {        list = new ArrayList<Integer>();        inOrder(root);        return list.get(k - 1);    }    public void inOrder(TreeNode root){        if(root == null){            return;        }        inOrder(root.left);        list.add(root.val);        inOrder(root.right);    }}

这样做的AC时间是4ms,时间挺久的,我又想到,没必要获取得到所有的中序遍历结果之后再停止,可以直接记数到了k停止即可,这样后面的结果就不用统计了。下面的代码时间是1ms.

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    List<Integer> list;    public int kthSmallest(TreeNode root, int k) {        list = new ArrayList<Integer>();        inOrder(root, k);        return list.get(k - 1);    }    public void inOrder(TreeNode root, int k){        if(root == null){            return;        }        inOrder(root.left, k);        list.add(root.val);        if(list.size() >= k){            return;        }        inOrder(root.right, k);    }}

看了高票答案之后想到,我根本不用保存节点的数值啊!!只要找到第k个数不就行了,其他的我都不用管!!所以,要用一个count来保存已经统计了多少数,当这个结果和k相同的时候就把数字返回就行。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    int ans;    int count;    public int kthSmallest(TreeNode root, int k) {        ans = 0;        count = 0;        inOrder(root, k);        return ans;    }    public void inOrder(TreeNode root, int k){        if(root == null){            return;        }        inOrder(root.left, k);        count++;        if(count == k){            ans = root.val;            return;        }        inOrder(root.right, k);    }}

这个AC的时间同样是1ms。

Date

2017 年 4 月 10 日

0 0
原创粉丝点击