zoukankan      html  css  js  c++  java
  • 二叉搜索树的第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;
        }
    }
    

      

  • 相关阅读:
    MySql锁机制
    Mysql存储引擎
    Linux 系统中安装mysql
    常见的系统架构
    Linux环境下搭建go开发环境
    Ajax概述
    正向代理和反向代理
    Mysql 存储过程以及在.net中的应用示例
    Mysql 事务
    Windows服务器实现自动化部署-Jenkins
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11208664.html
Copyright © 2011-2022 走看看