Leetcode 230. Binary search tree small element K (balance tree)

Source: Internet
Author: User

Topic

Given a binary search tree, write a function kthsmallest to find the k smallest element.

Description
You can assume that K is always valid, 1≤k≤ two forks to search for the number of tree elements.

Example 1:

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

   3  /  1   4     2

Output:1
Example 2:

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

       5      /      3   6    /    2   4  / 1

Output:3
Advanced:
If the binary search tree is often modified (insert/delete operations) and you need to find k the small value frequently, how would you optimize the kthSmallest function?

Exercises

Writing leetcode for the first time is not very good.

In the public definition of a function recursive sequence traversal, record the answer, found when return it can.

Do not spit slot variable name

/** * 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 index = 0, final_attack_ride;  void Solve(TreeNode* root, const int &k) {    if (root->left) {      Solve(root->left, k);    }    if (index >= k) return;    if (++index == k) {      final_attack_ride = root->val;      return;    }    if (root->right) {      Solve(root->right, k);    }  }  int kthSmallest(TreeNode* root, int k) {    Solve(root, k);    return final_attack_ride;  }};

Leetcode 230. Binary search tree small element K (balance tree)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.