Kth Smallest Element in a BST
2015-09-08 11:10
381 查看
解题思路:按树的中序遍历的方式,利用栈实现,第k个出栈的节点即是所求的。
Java
代码实现:
/**
* 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) {
TreeNode p=new TreeNode(0);
p=root;
Stack sk=new Stack();
sk.push(p);
while(p.left!=null){
sk.push(p.left);
p=p.left;
}
int i=0;
while(!sk.isEmpty()){
TreeNode q=new TreeNode(0);
q=(TreeNode)sk.pop();
i++;
if(i==k) return q.val;
if(q.right!=null) {
p=q.right;
sk.push(p);
while(p.left!=null){
sk.push(p.left);
p=p.left;
}
}
}
return 0;
}
}
原题题目:https://leetcode.com/problems/kth-smallest-element-in-a-bst/
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解