您的位置:首页 > 编程语言 > Go语言

Algorithms—230.Kth Smallest Element in a BST

2015-08-25 10:11 330 查看
思路:每次进来数一下左侧的节点数数,如果恰好比左侧节点数多1,则返回根节点,小于在左侧,大于在右侧。

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int kthSmallest(TreeNode root, int k) {
int left=f(root.left);
if (k==left+1) {
return root.val;
}
if (k<=left) {
return kthSmallest(root.left,k);
}
return kthSmallest(root.right,k-left-1);
}
public int f(TreeNode root){
if (root!=null) {
return 1+f(root.left)+f(root.right);
}
return 0;
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: