very simple and intuitive solution based on inorder traversal


  • 0
    I

    very simple and intuitive solution based on inorder traversal.

    int kthSmallest(TreeNode* root, int k)
    {
    	int counter = 0, val = 0;
    	kthSmallestHelper(root, counter, k, val);
    	return val;
    }
    
    void kthSmallestHelper(TreeNode* root, int &counter,int k, int &val)
    {
    	if (root == NULL) return;
    	kthSmallestHelper(root->left, counter, k, val);
    	if (++counter == k)  val = root->val;
    	kthSmallestHelper(root->right, counter, k, val);
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.