ð 230. äºåæ玢æ äžç¬¬Kå°çå çŽ
2022幎10æ10æ¥
- algorithm
ð 230. äºåæ玢æ äžç¬¬Kå°çå çŽ
éŸåºŠ: ð
é®é¢æè¿°
è§£æ³ 1
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int res = -1;
int curIndex = 0;
public int kthSmallest(TreeNode root, int k) {
// æè·¯ïŒ
// äžåº
mySol(root, k);
return res;
}
private void mySol(TreeNode root, int k) {
// éåœç»æ¢æ¡ä»¶
if(root == null) {
return;
}
mySol(root.left, k);
curIndex ++;
// System.out.println(root.val + " " + curIndex);
if(curIndex == k) {
res = root.val;
return;
}
if(res == -1) {
mySol(root.right, k);
}
}
}
èŸåº 1
è§£æ³ 2 - è¿é¶[é¢ç¹æ¥æŸ]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int kthSmallest(TreeNode root, int k) {
// æè·¯ïŒ
// åŠæéèŠé¢ç¹æ¥æŸïŒäœäºåæ åºå®äžåïŒé£ä¹å¯ä»¥å° root æ¯äžªèç¹å¯¹åºçåå©åæ°ç¡®å®
// é£ä¹åšé¢ç¹æ¥æŸæ¶ïŒåªéèŠå€ææ¯å·Šåæ è¿æ¯ å³åæ è¿æ¯åœåèç¹äžäžªæ¹åå³å¯
AA a = new AA(root);
return a.kthSmallest(k);
}
}
class AA {
TreeNode root;
HashMap<TreeNode, Integer> map;
public AA(TreeNode root) {
this.root = root;
this.map = new HashMap<>();
init(root);
}
public int kthSmallest(int k) {
TreeNode cur = root;
return mySol(cur, k);
}
public int mySol(TreeNode cur, int k) {
int left = 0;
if(map.containsKey(cur.left)) {
left = map.get(cur.left);
}
if(left == k - 1) {
return cur.val;
} else if(left > k - 1) {
// åŸå·Šåæ æ¥æŸ
return mySol(cur.left, k);
} else {
// åŸå³åæ æ¥æŸ
return mySol(cur.right, k - left - 1);
}
}
private int init(TreeNode root) {
// éåœç»æ¢æ¡ä»¶
if(root == null) {
return 0;
}
int left = init(root.left);
int right = init(root.right);
int c = left + right + 1;
map.put(root, c);
return c;
}
}
èŸåº 2
è§£æ³ 3 - è¿é¶[é¢ç¹å¢å + æ¥æŸ]
- åå© AVL 平衡æ