230. Kth Smallest Element in a BST**

来源:互联网 发布:python中import用法 编辑:程序博客网 时间:2024/05/22 11:30

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.

Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

Hint:

  1. Try to utilize the property of a BST.
  2. What if you could modify the BST node's structure?
  3. The optimal runtime complexity is O(height of BST).
My code:
/** * 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) {        int count = countNode(root.left);        if(k<=count) return kthSmallest(root.left, k);        else if (k==count+1) return root.val;        else return kthSmallest(root.right,k-count-1);    }    private int countNode(TreeNode root){        if (root==null) return 0;        else return countNode(root.left)+countNode(root.right) + 1;    }}

总结:看了答案。
Reference:
DFS in-order recursive:
public class Solution {    private static int number = 0;    private static int count = 0;    public int kthSmallest(TreeNode root, int k) {        count =k;        helper(root);        return number;    }    private void  helper(TreeNode root){        if(root.left!=null) helper(root.left);        count--;        if(count==0){            number = root.val;            return;        }        if(root.right!=null) helper(root.right);            }}

总结:关键在于helper(left)后再把count--;
DFS in-order iterative;
public class Solution {    public int kthSmallest(TreeNode root, int k) {        if(root==null) return 0;        Stack<TreeNode> stack = new Stack<TreeNode>();        while(root.left!=null){            stack.push(root);            root=root.left;        }        stack.push(root);        while(k!=0&&!stack.isEmpty()){            TreeNode cur = stack.pop();            k=k-1;            if(k==0) return cur.val;            if(cur.right!=null) stack.push(cur.right);        }        return root.val;            }}
总结:我的错误代码,没有考虑根节点右侧的情形,而且return的也不对。
正确代码:
public class Solution {    public int kthSmallest(TreeNode root, int k) {        if(root==null) return 0;        Stack<TreeNode> stack = new Stack<TreeNode>();        while(root!=null){            stack.push(root);            root=root.left;        }        while(k!=0){            TreeNode cur = stack.pop();            k--;            if(k==0) return cur.val;            TreeNode right = cur.right;            
    while(right!=null) {                stack.push(right);                right =right.left;            }

} return -1; }}
总结:关键在于
    while(right!=null) {                stack.push(right);                right =right.left;            }
此处可以一直找到某个节点cur的最左节点,为最小值。




0 0
原创粉丝点击