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); } }
相关文章推荐
- 命令行快速技巧:如何定位一个文件
- C#递归算法之分而治之策略
- 有关数据库SQL递归查询在不同数据库中的实现方法
- C#中的递归APS和CPS模式详解
- WinForm实现按名称递归查找控件的方法
- C#递归方法实现无限级分类显示效果实例
- jquery+CSS实现的多级竖向展开树形TRee菜单效果
- 使用SqlServer CTE递归查询处理树、图和层次结构
- C#递归算法之打靶算法分析
- C#中的尾递归与Continuation详解
- C#递归实现显示文件夹及所有文件并计算其大小的方法
- php递归创建目录的方法
- PHP递归创建多级目录
- cmd tree命令 以树形格式罗列文件
- Javascript递归打印Document层次关系实例分析
- 无限分级和tree结构数据增删改【附DEMO下载】
- 实例讲解jQuery EasyUI tree中state属性慎用
- 推荐8款jQuery轻量级树形Tree插件
- C#递归算法寻找数组中第K大的数
- C++使用递归方法求n阶勒让德多项式完整实例