面试题54:二叉搜索树的第k大节点


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

 

2、思路:二叉搜索树中序遍历的结果就是数值按照递增进行排序。因此只需要对二叉搜索树进行中序遍历,然后取出第k-1个数即可。

 

3、代码:

import java.util.ArrayList;
import java.util.List;

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

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

    }

}
*/
public class Solution {

    List<TreeNode> resultList=new ArrayList<>();

    TreeNode KthNode(TreeNode pRoot, int k)
    {
        if(pRoot==null){
            return null;
        }
        interTransform(pRoot);
        if(k<=resultList.size() && k>=1){
            return resultList.get(k - 1);
        }

        return null;
    }

    public  void interTransform(TreeNode pRoot){
        //左根右
        if(pRoot.left!=null){
            interTransform(pRoot.left);
        }

        resultList.add(pRoot);

        if(pRoot.right!=null){
            interTransform(pRoot.right);
        }

    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM