您的位置:首页 > 其它

LeetCode题解-230-Kth Smallest Element in a BST

2016-07-09 10:43 323 查看

原题



概览

BST是二叉查找树,它具有如下的性质:左子树中所有节点的值均小于根节点的值,右子树中所有节点的值均大于根节点的值。

解法1使用了迭代法;

解法2使用了递归法。

解法1

解题思路

使用迭代法。由于BST的性质,使用二叉树的中序遍历。中序遍历先访问到的节点的值较小,每访问一个节点计数值+1,当计数值到达K的时候该节点就是要访问的节点。
中序遍历的思路请见: LeetCode题解-94-Binary Tree Inorder Traversal

代码

public class Solution230_iterator {
public int kthSmallest(TreeNode root, int k) {
int count = 1;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);

while (!stack.empty()){
while (stack.peek() != null){
TreeNode currentNode = stack.peek();
stack.push(currentNode.left);
}
stack.pop();

if (!stack.isEmpty()){
TreeNode currentNode = stack.pop();
if (k == count++)
return currentNode.val;

stack.push(currentNode.right);
}
}
return -1;
}
}


解法2

解题思路

递归法,仍然是中序遍历。参考了3 ways implemented in JAVA: Binary Search, in-order iterative &
recursive public int kthSmallest(TreeNode root, int k) 
自己没有想出来递归方法,因为觉得 public int kthSmallest(TreeNode root, int k) 这样的函数不好构造递归。但是没有想到可以在构造一个新的函数,在 public int kthSmallest(TreeNode root, int k) 中调用该函数。

代码

public class Solution230_recursive {
private static int count = 0;
private static int number = 0;

public int kthSmallest(TreeNode root, int k) {
count = k;
helper(root);
return number;
}

private void helper(TreeNode root) {
if (root.left != null)
helper(root.left);

count--;
if (count == 0) {
number =  root.val;
return;
}
if (root.right != null)
helper(root.right);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode Tree 递归