230. Kth Smallest Element in a BST

/**
 * 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) {
        //二叉搜索树,左子如果不是空,则必小于该节点
        //右子不为空,则必大于该节点。同样每个分支也都满足这个条件
        
        Stack<TreeNode> st=new Stack<TreeNode>();
        
        if(root==null)
            return 0;
        int res=0;
        int count=0;
        
        TreeNode temp=root;
        
        while(temp!=null||!st.isEmpty())
        {
            if(temp!=null)
            {
                st.push(temp);
                temp=temp.left;
            }
            else if(!st.isEmpty())
            {
                temp=st.pop();
                count++;
                if(count==k)
                {
                    res=temp.val;
                    break;
                }
                if(temp.right!=null)
                    temp=temp.right;
                else
                    temp=null;
            }
        }
        
        return res;
        
        
        
    }
}

 

posted @ 2016-04-02 11:11  阿怪123  阅读(95)  评论(0编辑  收藏  举报