码迷,mamicode.com
首页 > 其他好文 > 详细

230. Kth Smallest Element in a BST

时间:2017-06-30 17:18:37      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:problems   com   code   stack   blog   public   int   null   while   

https://leetcode.com/problems/kth-smallest-element-in-a-bst/#/solutions

public int kthSmallest(TreeNode root, int k) {
    Stack<TreeNode> stack = new Stack<TreeNode>();
    TreeNode cur = root;
    while(cur != null || !stack.isEmpty()){
        while(cur != null){
          stack.push(cur);
          cur = cur.left;
        } 
        TreeNode node = stack.pop();
        if(--k == 0) return node.val;
        cur = node.right;
    }
    return root.val;
}
       

递归:  

public class Solution {
    int count = 0;
    
    public int kthSmallest(TreeNode root, int k) {
        List<Integer> res = new ArrayList<Integer>();
        res.add(null);
        helper(root, k, res);
        return res.get(0);
    }
    
    public void helper(TreeNode root, int k, List<Integer> res) {
        if (root == null) return;
        helper(root.left, k, res);
        count++;
        if (count == k) res.set(0, root.val);
        helper(root.right, k, res);
    }
}

  

230. Kth Smallest Element in a BST

标签:problems   com   code   stack   blog   public   int   null   while   

原文地址:http://www.cnblogs.com/apanda009/p/7099223.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!