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

二叉搜索树的特点、查找、插入、删除、建立空树:

https://www.cnblogs.com/LydiammZuo/p/11893982.html

 

1.递归(用二叉树的中序遍历)

 

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {
     int count=0;//计数器:当前访问了多少个结点
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        if(pRoot!=null){ //中序遍历寻找第k个
            TreeNode node1=KthNode(pRoot.left,k);//左子树分支总返回给node1
            if(node1!=null) return node1;//将node1 return给上一层
            
            if(++count==k) return pRoot;//找到了第k小的结点
            
            TreeNode node2=KthNode(pRoot.right,k);//右子树分支总返回给node2
            if(node2!=null) return node2;
        }
        return null;//向上一层返回
    }
}

 

2.非递归中序遍历

import java.util.*;
public class Solution {
    TreeNode KthNode(TreeNode root, int k)
    {
        int count=0;
        if(root==null) return null;
        Stack<TreeNode>s=new Stack<>();
        TreeNode p=root;
        while(!s.isEmpty()||p!=null){
            if(p!=null){//根结点入栈、其左孩子存在则入栈
                s.push(p);
                p=p.left;
            }
            else {//栈不空的情况下出栈
                p=s.pop();
                if(++count==k) return p;//找到了第k小的结点就返回
                p=p.right;//每次出栈都判断下该出栈节点的右孩子是否存在,存在则入栈
            }
        }
        return null;
    }


}

 

posted @ 2020-04-07 16:58  冰河入梦~  阅读(288)  评论(0编辑  收藏  举报