剑指offer (62)

题目 : 给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。

思路 : 二叉搜索树的中序遍历就是从小到大排序,所以只要找到中序遍历的第K个节点即可;可以使用链表存储节点,要注意边界条件,K可能不是个有效值

import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
	static TreeNode root = null;
	ArrayList<TreeNode> list = new ArrayList<>();
	// 寻找倒数第k小的节点
	TreeNode kminNode(TreeNode root, int k) {
		inOrder(root);
		if (k > 0 && list.size() >= k) {
			return list.get(k - 1);
		} else
			return null;
	}
	// 根据中序遍历将数值存进一个链表
	public void inOrderLink (TreeNode root) {
		if (root == null) {
			return;
		}
		inOrder(root.left);
		list.add(root);
		inOrder(root.right);
	}

	// 查找节点
	public TreeNode find(TreeNode root, int key) {
		TreeNode current = root;
		while (current != null) {
			if (current.value > key) {// 当前值比查找值大,搜索左子树
				current = current.left;
			} else if (current.value < key) {// 当前值比查找值小,搜索右子树
				current = current.right;
			} else {
				return current;
			}
		}
		return null;// 遍历完整个树没找到,返回null
	}
	// 插入节点构建搜索二叉树
	public boolean insert(int data) {
		TreeNode newNode = new TreeNode(data);
		if (root == null) {// 当前树为空树,没有任何节点
			root = newNode;
			return true;
		} else {
			TreeNode current = root;
			TreeNode parent = null;
			while (current != null) {
				parent = current;
				if (data < current.value) {// 当前值比插入值大,搜索左子节点
					current = current.left;
					if (current == null) {// 左子节点为空,直接将新值插入到该节点
						parent.left = newNode;
						return true;
					}
				} else {
					current = current.right;
					if (current == null) {// 右子节点为空,直接将新值插入到该节点
						parent.right = newNode;
						return true;
					}
				}
			}
		}
		return false;
	}
}
class TreeNode {
	int value = 0;
	TreeNode left = null;
	TreeNode right = null;
	public TreeNode(int value) {
		this.value = value;
	}
	// 为了显示方法,我们重新toString
	@Override
	public String toString() {
		return "TreeNode [value=" + value + "]";
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值