剑指offer——二叉搜索树的第k个结点(覆盖TreeSet的compare方法)

题目描述

给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。



错误思路:后序遍历,用count记数,等于k时返回。这个做法没有考虑到如下情况。这样后序遍历是不行的。

这里应该是中序遍历。

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
   int index = 0; //计数器
	TreeNode KthNode(TreeNode root, int k)
	{
		if(root != null){ //中序遍历寻找第k个
			TreeNode node = KthNode(root.left,k);
			if(node != null)
				return node;
			index ++;
			if(index == k)
				return root;
			node = KthNode(root.right,k);
			if(node != null)
				return node;
			}
			return null;
	}


}



另外一种:

解题思路:

用TreeSet全部加进去一遍。重写compare方法。然后迭代计数。将该类对象作为实际参数传递给TreeSet集合的构造函数。

TreeSet集合排序有两种方式,Comparable和Comparator区别: 
 1:让元素自身具备比较性,需要元素对象实现Comparable接口,覆盖compareTo方法。 
 2:让集合自身具备比较性,需要定义一个实现了Comparator接口的比较器,并覆盖compare方法, 
  并将该类对象作为实际参数传递给TreeSet集合的构造函数。 第二种方式较为灵活。 

参考文献:http://blog.csdn.net/geek_ymv/article/details/38147047

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
public class Solution {
    TreeSet<TreeNode>treeSet = new TreeSet<>(new TreeNodeComparator());
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        if(pRoot==null||k==0)return null;
		preorder(pRoot);
		Iterator<TreeNode>iterator = treeSet.iterator();
		int count=1;
		while(iterator.hasNext()){
			if(count==k)return iterator.next();
			iterator.next();
			count++;
		}
		return null;
    }
	public void preorder(TreeNode pRoot){
		treeSet.add(pRoot);
		if(pRoot.left!=null)preorder(pRoot.left);
		if(pRoot.right!=null)preorder(pRoot.right);
	}

	
	class TreeNodeComparator implements Comparator<TreeNode>{
		@Override
		public int compare(TreeNode o1, TreeNode o2) {
			return o1.val-o2.val;
		}
	}
	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值