• 230.Kth Smallest Element in a BST


        /*
         * 230.Kth Smallest Element in a BST 
         * 2016-6-14 By Mingyang
         * 我的第一个想法就是这个题目肯定用dfs,然后我们可以用stack来做,也可以直接dfs来做
         * 后面又遇到改进型算法,不过时间都差不多
         */
        private int counttt = 0;
        private int resss = 0;
        public int kthSmallest1(TreeNode root, int k) {
            if (root == null)
                return 0;
            dfs(root, k);
            return resss;
        }
        public void dfs(TreeNode root, int k) {
            if (root == null)
                return;
            dfs(root.left, k);
            if (counttt == k - 1) {
                resss = root.val;
            }
            counttt++;
            dfs(root.right, k);
        }
        public int kthSmallest(TreeNode root, int k) {
            Stack<TreeNode> stack = new Stack<TreeNode>();
            TreeNode p = root;
            int result = 0;
            // 不断的dfs,利用左中右的遍历方式进行遍历,然后依次取到最后的值
            while (!stack.isEmpty() || p != null) {
                if (p != null) {
                    stack.push(p);
                    p = p.left;
                } else {
                    TreeNode t = stack.pop();
                    k--;
                    if (k == 0)
                        result = t.val;
                    p = t.right;
                }
            }
            return result;
        }
        // 这个方法的复杂度是n,首先countNode毫无疑问是n,然后整个方程复杂度就是
        //O(n) = n/2+n/4+n/8…..因为一开始是二分之n,只计算了root的left的node数,然后继续往下的时候
        //node的总数每次都在变小,而且都是二分之一的变小
        public int kthSmallest2(TreeNode root, int k) {
            int count = countNodes2(root.left);
            if (k <= count) {
                return kthSmallest2(root.left, k);
            } else if (k > count + 1) {
                return kthSmallest2(root.right, k-1-count); // 1 is counted as current node
            }
          //唯一退出的情况就是count+1等于k的时候,我们知道root就是那个想要找到的值,非常精彩的解法
            return root.val;
        }
        public int countNodes2(TreeNode n) {
            if (n == null) return 0;
            return 1 + countNodes2(n.left) + countNodes2(n.right);
        }
  • 相关阅读:
    K-邻近算法
    算法
    (12)ubunto 快捷键
    (38)C#IIS
    RichEditControl(富文本控件)
    Gaugecontrol(测量仪器图形控件)
    鏖战字符串
    bzoj3713 [PA2014]Iloczyn|暴力(模拟)
    约会安排HDU
    hdu4614 线段树+二分 插花
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5586458.html
Copyright © 2020-2023  润新知