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

230. Kth Smallest Element in a BST

时间:2018-08-09 19:28:13      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:sse   code   list   val   conf   turn   arraylist   count   bin   

230. Kth Smallest Element in a BST



// dfs inroder traversal recursively  , record the first k nodes , return the kth node 

 Solution {
    List<Integer> result = new ArrayList<>();
    public int kthSmallest(TreeNode root, int k) {
      if(root == null){
        return 0;
      }
      inorder(root, k);
      return result.get(k - 1);
    }
    private void inorder(TreeNode root, int k){
      if(result.size() >= k){
        return;
      }
      if(root == null){
        return;
      }
      inorder(root.left, k);
      result.add(root.val);
      inorder(root.right, k);
    }
}




DFS in-order recursive :  idk the confusion discussed in class and don’t know how to write this recursively
// inroder traversal recursively, no need to record the the first k-1 elements , only return the kth 

public class Solution {
    public int kthSmallest(TreeNode root, int k) {
        List<Integer> res = new ArrayList<>();
        inOrder(res, root, k);
        return res.size() >= k ? res.get(k - 1) : 0;
    }
    
    private void inOrder(List<Integer> res, TreeNode root, int k) {
        if (root == null || res.size() >= k)  return;
        inOrder(res, root.left, k);
        res.add(root.val);
        inOrder(res, root.right, k);
    }
}




DFS in-order iterative:

  public int kthSmallest(TreeNode root, int k) {
        Stack<TreeNode> st = new Stack<>();
        
        while (root != null) {
            st.push(root);
            root = root.left;
        }
            
        while (k != 0) {
            TreeNode n = st.pop();
            k--;
            if (k == 0) return n.val;
            TreeNode right = n.right;
            while (right != null) {
                st.push(right);
                right = right.left;
            }
        }
        
        return -1; // never hit if k is valid
  }

这个不是自己写的, 自己写的 会叫 pushleft, 虽然都是一样的, 但是要自己写, 自己理解的。。




Binary Search (dfs): most preferable 
I don’t understand this solution, might be discussed in the future bst class 

  public int kthSmallest(TreeNode root, int k) {
        int count = countNodes(root.left);
        if (k <= count) {
            return kthSmallest(root.left, k);
        } else if (k > count + 1) {
            return kthSmallest(root.right, k-1-count); // 1 is counted as current node
        }
        
        return root.val;
    }
    
    public int countNodes(TreeNode n) {
        if (n == null) return 0;
        
        return 1 + countNodes(n.left) + countNodes(n.right);
    }
 

 

230. Kth Smallest Element in a BST

标签:sse   code   list   val   conf   turn   arraylist   count   bin   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9450912.html

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