leetcode--Kth Smallest Element in a BST
来源:互联网 发布:js 特殊字符校验 编辑:程序博客网 时间:2024/06/11 03:06
Given a binary search tree, write a function kthSmallest
to find thekth 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:
- Try to utilize the property of a BST.
- What if you could modify the BST node's structure?
- The optimal runtime complexity is O(height of BST).
题意:在BST树中,查找第k小的节点值
分类:二叉树
解法1:BST树很多问题我们都可以使用中序遍历来解决,这个也不例外
我们设置一个当前访问的元素个数cur,在中序遍历过程中,每要访问一个节点,cur加1
当cur和k相等时,这就是我们要找的节点,返回即可
利用递归来进行中序遍历,如果左子树找不到,则判断是不是当前节点,不是,则在右子树接着找
如果左子树找到了,直接返回
/** * 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 cur = 0; public int kthSmallest(TreeNode root, int k) { TreeNode res = inorder(root,k); if(res!=null) return res.val; return -1; } public TreeNode inorder(TreeNode root,int k){ if(root==null) return null; if(root.left!=null){ TreeNode left = inorder(root.left,k);//先在左子树找 if(left!=null) return left;//如果找到了,返回 } cur++;//每次访问节点,都加1 if(cur==k) return root;//判断是不是当前节点 if(root.right!=null){//最后在右子树找 TreeNode right = inorder(root.right,k); if(right!=null) return right; } return null; }}
0 0
- #leetcode#Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- Leetcode|Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- 【LeetCode】Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- leetcode: Kth Smallest Element in a BST
- Leetcode: Kth Smallest Element in a BST
- [LeetCode] Kth Smallest Element in a BST
- [LeetCode]Kth Smallest Element in a BST
- [Leetcode]Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- [Leetcode]Kth Smallest Element in a BST
- Leetcode: Kth Smallest Element in a BST
- Matlab中varargin函数
- hdu5319 Painter
- malloc(0)
- 机试算法讲解:第50题 动态规划之拦截导弹
- poj-3083 Children of the Candy Corn-DFS+BFS
- leetcode--Kth Smallest Element in a BST
- 多线程(join和yield)
- Lucene七(搜索)
- Servlet学习
- NYOJ269VF【dp】
- 回溯法解决N皇后问题
- java.lang.ClassNotFoundException: Didn't find class "*****Activity" on path: /data/app/*******.apk
- HDU 1203
- 6.地址,Block,SEL,多态