一个二叉排序树,输入k,输出第k小的节点值


import java.util.Scanner;

public class Client_port {

	public static void main(String[] args) {
		Client_port cp = new Client_port();
		cp.insert_node("5");
		cp.insert_node("3");
		cp.insert_node("6");
		cp.insert_node("2");
		cp.insert_node("4");
		cp.insert_node("1");
		// 创建一个搜索树
		Scanner s = new Scanner(System.in);
		int k = s.nextInt();
		String st = mid_select(cp.getRoot());// 对节点值中序排序
		System.out.println(st.charAt(k - 1));// 获取第k个,因为从0开始
	}

	private static String mid_select(Node root) {
		// TODO Auto-generated method stub
		String s = "";
		if (root != null)
			s = mid_select(root.getLchild()) + root.getVal() + mid_select(root.getRchild());
		return s;
	}

	static Node root;

	public Node getRoot() {
		return root;
	}

	public void setRoot(Node root) {
		this.root = root;
	}

	private void insert_node(String s) {
		// TODO Auto-generated method stub
		Node n = new Node(s);
		if (root == null) {// 如果根节点为null,当前就是根节点
			root = n;
			root.setLchild(null);
			root.setRchild(null);
		} else {
			// 创建一个临时节点,通过遍历确认为当前节点最终位置
			// 临时根节点,用来保存当前的父节点
			Node tmp = root;
			Node tmp_root;
			while (true) {
				tmp_root = tmp;// 当前节点作为根节点开始遍历
				if (Integer.valueOf(tmp.getVal()) < Integer.valueOf(n.getVal())) {// 新节点的值比当前这个大,那就往他的右边放
					tmp = tmp.getRchild();// 获取右孩子,如果右孩子为null就将该点放入,否则继续找
					if (tmp == null) {
						tmp_root.setRchild(n);
						return;
					}
				} else {
					tmp = tmp.getLchild();
					if (tmp == null) {
						tmp_root.setLchild(n);
						return;
					}
				}
			}
		}
	}
}

class Node {
	private String val;
	private Node lchild;
	private Node rchild;

	public Node(String val) {
		// TODO Auto-generated constructor stub
		this.val = val;
	}

	public String getVal() {
		return val;
	}

	public void setVal(String val) {
		this.val = val;
	}

	public Node getLchild() {
		return lchild;
	}

	public void setLchild(Node lchild) {
		this.lchild = lchild;
	}

	public Node getRchild() {
		return rchild;
	}

	public void setRchild(Node rchild) {
		this.rchild = rchild;
	}

}

结果:

发布了233 篇原创文章 · 获赞 20 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_42565135/article/details/103689034
今日推荐