[Leetcode] Kth smallest Element in a BST

Source: Internet
Author: User

This link suggests a concise C + + recursive solution. The original code may is hard-understand at first and I have rewritten the code below. Need to run some examples and it to see how it works.

1 classSolution {2  Public:3     intKthsmallest (treenode* root,intk) {4         returnsmallest (root, k);5     }6 Private:7     intSmallest (treenode* node,int&k) {8         if(!node)return-1;9         intval = Smallest (node-Left , k);Ten         if(!k)returnVal; One         if(!--k)returnNode-Val; A         returnSmallest (node-Right , k); -     } -};

The same author also posts three solutions which is more space-efficient in this link. All of them reduce the o (n) space of the above code to O (k) space by using some nice data structures.

Personally I really love the soltuion using deque and I had rewritten it below.

1 classSolution {2  Public:3     intKthsmallest (treenode* root,intk) {4treenode* node =Root;5Deque<treenode*>nodes;6          while(true) {7              while(node) {8 Nodes.push_front (node);9                 if(Nodes.size () >k)Ten Nodes.pop_back (); Onenode = nodeLeft ; A             } -node =Nodes.front (); - Nodes.pop_front (); the             if(!--k)returnNode-Val; -node = nodeRight ; -         } -     } +};

[Leetcode] Kth smallest Element in a BST

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.