zoukankan      html  css  js  c++  java
  • 剑指 Offer 54. 二叉搜索树的第k大节点

    给定一棵二叉搜索树,请找出其中第k大的节点。

    示例 1:

    输入: root = [3,1,4,null,2], k = 1
       3
      / 
     1   4
      
       2
    输出: 4

    示例 2:

    输入: root = [5,3,6,2,4,null,null,1], k = 3
           5
          / 
         3   6
        / 
       2   4
      /
     1
    输出: 4

    分析:中序遍历 结果有小到大

    // 打印中序遍历
    void dfs(TreeNode root) {
        if(root == null) return;
        dfs(root.left); //
        System.out.println(root.val); //
        dfs(root.right); //
    }

    中序遍历倒序 由大到小

    // 打印中序遍历倒序
    void dfs(TreeNode root) {
        if(root == null) return;
        dfs(root.right); //
        System.out.println(root.val); //
        dfs(root.left); //
    }

    使用中序遍历倒序

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        private ArrayList<Integer> res = new ArrayList<Integer>(); 
        public int kthLargest(TreeNode root, int k) {
    
            inOrder(root);
            int result = res.get(k-1);
            return result;
        }
    
        public void inOrder(TreeNode root)
        {
            if(root == null) return;
            inOrder(root.right);
            res.add(root.val);
            inOrder(root.left);
        }
    }

    简化版

    class Solution {
        int res, k;
        public int kthLargest(TreeNode root, int k) {
            this.k = k;
            dfs(root);
            return res;
        }
        void dfs(TreeNode root) {
            if(root == null) return;
            dfs(root.right);
            if(k == 0) return;
            if(--k == 0) res = root.val;
            dfs(root.left);
        }
    }
  • 相关阅读:
    B+树的Copy-on-Write设计
    so库链接和运行时选择哪个路径下的库?
    Xapian索引-文档检索过程分析之匹配百分比
    Xapian索引-文档检索过程分析
    Xapian的内存索引-添加文档
    Xapian的内存索引
    Xapian使用入门
    一个std::sort 自定义比较排序函数 crash的分析过程
    编译GCC4.8.2
    使用C++11的一点总结
  • 原文地址:https://www.cnblogs.com/kpwong/p/14689404.html
Copyright © 2011-2022 走看看