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);
        }
    }
  • 相关阅读:
    还不知道spring的RestTemplate的妙用吗
    【学习笔记】机器学习之特征工程
    《饥饿的盛世》总结
    我是如何解决java.security.cert.CertPathValidatorException异常的
    《机器学习
    2018年总结
    元类实现ORM
    元类
    python中的装饰器
    python中的闭包
  • 原文地址:https://www.cnblogs.com/kpwong/p/14689404.html
Copyright © 2011-2022 走看看