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