34、二叉搜索树的第k个结点

版权声明:版权所有 https://blog.csdn.net/qq_42253147/article/details/86501931

题目

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

思路

  • 中序遍历结果就是从小到大的排序,然后确定第k位的数据

  • 参考剑指offer就是:【】23、二叉搜索树与双链表】

代码

import java.util.ArrayList;
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

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

    }

}
*/
public class Solution {
    ArrayList<TreeNode> list = new ArrayList<>();
    TreeNode temp = null;
    int length = 0;
    TreeNode KthNode(TreeNode pRoot,int k){
        if(pRoot==null ||k<=0)
            return null;
        if(pRoot.left!=null)
            KthNode(pRoot.left,k);
         length++;
        if(pRoot!=null){
            list.add(pRoot);
        }
        if(length==k)
            temp=list.get(k-1);
            
        if(pRoot.right!=null)
            KthNode(pRoot.right,k);
    return temp; 
    }
    
}

猜你喜欢

转载自blog.csdn.net/qq_42253147/article/details/86501931