首页 > 其他 > 详细

230. Kth Smallest Element in a BST

时间:2016-04-02 12:03:52      阅读:326      评论:0      收藏:0      [点我收藏+]
/**
 * 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;
        
        
        
    }
}

 

230. Kth Smallest Element in a BST

原文:http://www.cnblogs.com/aguai1992/p/5347125.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!