面试题:二叉搜索树的第K个节点

Posted aaron12

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了面试题:二叉搜索树的第K个节点相关的知识,希望对你有一定的参考价值。

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

思路1:非递归中序遍历

import java.util.Stack;
public class Solution {
    TreeNode KthNode(TreeNode root, int k){
        if(root==null||k==0) return null;
        int count=0;
        Stack<TreeNode> stack=new Stack<>();
        while(root!=null||!stack.isEmpty()){
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root=stack.pop();
            count++;
            if(count==k) return root;
            root=root.right;
        }
        return null;
    }
}

思路2:递归中序遍历  这个不是很懂

//思路:二叉搜索树按照中序遍历的顺序打印出来正好就是排序好的顺序。
//     所以,按照中序遍历顺序找到第k个结点就是结果。
public class Solution {
   int index = 0; //计数器
    TreeNode KthNode(TreeNode root, int k)
    {
        if(root != null){ //中序遍历寻找第k个
            TreeNode node = KthNode(root.left,k);
            if(node != null)
                return node;
            index ++;
            if(index == k)
                return root;
            node = KthNode(root.right,k);
            if(node != null)
                return node;
        }
        return null;
    }
}

 

以上是关于面试题:二叉搜索树的第K个节点的主要内容,如果未能解决你的问题,请参考以下文章