[LeetCode][JavaScript]Kth Smallest Element in a BST

來源:互聯網
上載者:User

標籤:

Kth Smallest Element in a BST

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.

Follow up:

What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

Hint:

  1. Try to utilize the property of a BST.
  2. What if you could modify the BST node‘s structure?
  3. The optimal runtime complexity is O(height of BST).

https://leetcode.com/problems/kth-smallest-element-in-a-bst/

 

 

 

 

這題資訊量好大,先是最簡單粗暴的解法。

二叉搜尋樹的特性,先序遍曆的輸出就是排序的結果。

 1 /** 2  * Definition for a binary tree node. 3  * function TreeNode(val) { 4  *     this.val = val; 5  *     this.left = this.right = null; 6  * } 7  */ 8 /** 9  * @param {TreeNode} root10  * @param {number} k11  * @return {number}12  */13 var kthSmallest = function(root, k) {14     var count = 0;15     var isFound = false;16     var res = null;17     inorder(root);18     return res;19 20     function inorder(node){21         if(node !== null && !isFound){22             inorder(node.left);23             count++;24             if(count === k){25                 res = node.val;26                 isFound = true;27                 return;28             }29             inorder(node.right);30         }31     }32 };

 

 

    [LeetCode][JavaScript]Kth Smallest Element in a BST

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.