K-th node binary search tree: to prove safety Offer sixty-two

Casual working

Given a binary search tree, please find the first k smaller nodes therein. For example, (5,3,7,2,4,6,8), the numerical values ​​according to the third junction point is 4 summary.

Thinking

Binary search tree? Not that it ordered in order to find out the first of several small, it can be positioned directly in the order sequence.

Code

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;
    }

}
Published 84 original articles · won praise 53 · views 7382

Guess you like

Origin blog.csdn.net/weixin_44015043/article/details/105422808