LeetCode-230 Kth Smallest Element in a BST

Title Description

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note: 
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

 

Subject to the effect

Given a binary search, the nodes in the tree to find the required small numbers of k.

 

Examples

E1

Input: root = [3,1,4,null,2], k = 1
   3
  / \
 1   4
  \
   2
Output: 1

E2

Input: root = [5,3,6,2,4,null,null,1], k = 3
       5
      / \
     3   6
    / \
   2   4
  /
 1
Output: 3

 

Problem-solving ideas

Simple traversal sequence again, the use of an integer value record access to several tree node, if the k-th access node, recording the node integer value to return.

 

Complexity Analysis

Time complexity: O (N)

Space complexity: O (1)

 

Code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 * / 
Class Solution {
 public :
     int kthSmallest (the TreeNode * the root, int K) {
         int RES = 0 , I = 0 ;
         // preorder 
        inorder (root, k, i, res);
        
        return res;
    }
    
    void InOrder (the TreeNode Node *, int & K, int & I, int & RES) {
         IF (Node == NULL)
             return ;
         // traverse the left node 
        InOrder (node-> left, K, I, RES);
         / / the number of nodes to access a plus, if the visited nodes k, the integer value of the node records the result, and returns 
        ++ I;
         IF (I == k) {
            res = node->val;
            return;
        }
        // If k has not access nodes, the node continues right to access node 
        InOrder (node-> right, k, I, RES);
    }
};

 

Guess you like

Origin www.cnblogs.com/heyn1/p/11095773.html