Fork me on GitHub

二叉搜索树的第k个结点

题目描述

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

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

public class Main60 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TreeNode root = new TreeNode(8);
		root.left = new TreeNode(6);
		root.left.left = new TreeNode(5);
		root.left.right = new TreeNode(7);
		
		root.right = new TreeNode(10);
		root.right.left = new TreeNode(9);
		root.right.right = new TreeNode(11);
		System.out.println(Main60.KthNode(root, 4).val);
	}
	
	public static class TreeNode {
	    int val = 0;
	    TreeNode left = null;
	    TreeNode right = null;

	    public TreeNode(int val) {
	        this.val = val;
	    }
	}
	
	static int count = 0;
	public static TreeNode KthNode(TreeNode pRoot, int k){
		if(count > k || pRoot == null)
            return null;
        TreeNode p = pRoot;
        Stack<TreeNode> myStack = new Stack<TreeNode>();
        TreeNode myNode = null;
        while(p != null || !myStack.isEmpty()){
            while(p != null){
                myStack.push(p);
                p = p.left;
            }
            TreeNode node = myStack.pop();
            count++;
            if(count == k){
                myNode = node;
            }
            p = node.right;
        }
        return myNode;
    }
}

  

posted @ 2019-07-18 17:18  gentleKay  阅读(152)  评论(0编辑  收藏  举报