面试题:二叉搜索树的第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;
    }
}
原文地址:https://www.cnblogs.com/Aaron12/p/9539309.html