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

    这里要注意题目的说法,课本、牛客 都是第K个节点  ,LeetCode 上说的是第K大的节点。大家都知道 二叉搜索树的中序遍历

    可以得到一个递增序列,那么 第K个, 和第K大 是稍稍不一样的。

    LeetCode

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        int k;
        int target;
        public int kthLargest(TreeNode root, int k) {
                this.k = k ;
                dfs(root);
                return target;
        }
        
        void dfs(TreeNode root){
            if(root == null) return;
            dfs(root.right);
            if(k == 0) return;
            if(--k == 0)
            target = root.val;
            dfs(root.left);
        }
    }

    牛客

    /*
    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
    
        public TreeNode(int val) {
            this.val = val;
    
        }
    
    }
    */
    public class Solution {
        TreeNode res;
        int count = 0;
        TreeNode KthNode(TreeNode pRoot, int k)
        {
            if(pRoot == null || k <= 0){
                return null;
            }
            dfs(pRoot,k);
            return res;
        }
        void dfs(TreeNode root, int k){
            if(count < k && root.left != null){
                dfs(root.left,k);
            }
            
            if(++count == k){
                res = root;
                return;
            }
            if(count < k && root.right != null){
                dfs(root.right,k);
            }
        }
    
    }
  • 相关阅读:
    js检验文件格式
    java判空工具类
    $(document).ready() 是个什么函数?为什么要用它?
    Maven 手动添加jar
    java深克隆
    cors跨域详解
    常见异常类总结
    Spring事务回滚机制
    Java获取13位毫秒级时间戳
    JSON 字符串转换为 Map
  • 原文地址:https://www.cnblogs.com/peanut-zh/p/14148914.html
Copyright © 2011-2022 走看看