Kth Smallest Element in a BST

来源:互联网 发布:程序员工作体会 编辑:程序博客网 时间:2024/06/05 17:44

Given a binary search tree, write a function kthSmallest to find the kth smallest 

element in it.

Note:

You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
找到二叉搜索树中的第k小的元素。
使用栈,如果有左子树,入栈,否则出栈,k--,k=0则当地节点就是要找的节点,
否则寻找右子树。
因为最小的点在最左下,所以一直操作左子树。
public class Solution {    public int kthSmallest(TreeNode root, int k) {        Stack<TreeNode> stack=new Stack<TreeNode>();TreeNode p=root;while(p!=null||!stack.isEmpty()){if(p!=null){stack.push(p);p=p.left;}else{TreeNode t=stack.pop();k--;if(k==0)return t.val;p=t.right;}}return 0;    }}


0 0
原创粉丝点击