T59:二叉搜素树的第K个节点(Java)

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

分析:二叉搜素树就是二叉树的中序遍历

import java.util.Stack;

public class KthNode2 {
	public static class TreeNode {
	    int val = 0;
	    TreeNode left = null;
	    TreeNode right = null;

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

	    }

	}
	
	public static TreeNode KthNode(TreeNode pRoot, int k) {   
		 if(pRoot==null||k==0){
	    	return null;
	    }
	     int count =0;
	     Stack<TreeNode> stack=new Stack<TreeNode>();
	    while(pRoot!=null||!stack.isEmpty()){
	    	while(pRoot!=null){
	    	    stack.push(pRoot);
	    		pRoot=pRoot.left;
	    	}
            if(!stack.isEmpty()){
	    	   count++;
	    	   pRoot=stack.pop();
	    	   if(count==k){
	    			return pRoot;
	    		}
	    	pRoot=pRoot.right;
	    	}
	    }
	    		return null;
	    }
	 
	 public static void main(String[] args) {
		 TreeNode head=new TreeNode(5);
		 head.left=new TreeNode(3);
		 head.right=new TreeNode(7);
		 head.left.left=new TreeNode(2);
		 head.left.right=new TreeNode(4);
		 head.right.left=new TreeNode(6);
		 head.right.right=new TreeNode(8);
		 System.out.println(KthNode(head,8));
		 
		 
	}
 }

是递增的树。

猜你喜欢

转载自blog.csdn.net/qq_40516725/article/details/84991915