首页 > 编程语言 > 详细

Java for LeetCode 230 Kth Smallest Element in a BST

时间:2015-09-22 18:47:48      阅读:242      评论:0      收藏:0      [点我收藏+]

解题思路:

直接修改中序遍历函数即可,JAVA实现如下:

int res = 0;
	int k = 0;

	public int kthSmallest(TreeNode root, int k) {
		this.k = k;
		inorderTraversal(root);
		return res;
	}

	public List<Integer> inorderTraversal(TreeNode root) {
		List<Integer> list = new ArrayList<Integer>();
		if (root == null)
			return list;
		if (root.left != null && list.size() < k)
			list.addAll(inorderTraversal(root.left));
		list.add(root.val);
		if (root.right != null && list.size() < k)
			list.addAll(inorderTraversal(root.right));
		if(list.size()==k){
			res=list.get(k-1);
			return list;
		}
		return list;
	}

 

Java for LeetCode 230 Kth Smallest Element in a BST

原文:http://www.cnblogs.com/tonyluis/p/4829314.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!