K-th tree node wins the offer 62. Binary Search Tree

Title Description

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.

Problem-solving ideas

二叉搜索树按照中序遍历的顺序打印出来正好就是排序好的顺序。
所以,按照中序遍历顺序找到第k个结点就是结果。
 

code show as below

   int index = 0; // counter 
            the TreeNode KthNode (the root the TreeNode, int k) 
            { 
                IF (! the root = null ) { // preorder find the k-th 
                    the TreeNode Node = KthNode (root.left, k);
                     IF (Node ! = null )
                         return Node; 
                    index ++ ;
                     IF (index == K)
                         return the root; 
                    Node = KthNode (root.right, K);
                    if(node != null)
                        return node;
                }
                return null;
            }

 

Guess you like

Origin www.cnblogs.com/Transkai/p/11422728.html