• 剑指62.二叉搜索树的第k个结点


    题目描述

    给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4。
     

    思路

    如果中序遍历一棵二叉搜索树,则遍历序列的数值是递增排序的。因此,只需要在中序遍历节点的过程中,判断当前遍历的节点是否为第k个节点就行了

    解法

    /*
    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
    
        public TreeNode(int val) {
            this.val = val;
        }
    }
    */
    public class Solution {
        private int index = 1;
        private TreeNode ans = null;
        TreeNode KthNode(TreeNode pRoot, int k) {
            if (pRoot == null || k <= 0)
                return null;
            getKthNode(pRoot,k);
            return ans;
        }
        // 找第k小的节点
        private void getKthNode(TreeNode node, int k){
            if (ans == null){ // 剪枝操作,ans为空时说明还没找到第k个节点,如果找到了就没必要遍历其他节点了
                if (node.left != null)
                    getKthNode(node.left,k);
                if (index == k){
                    ans = node;
                }
                index++;
                if (node.right != null)
                    getKthNode(node.right,k);
            }
        }
        
        // 举一反三:找第k大的节点
        // 思路:只需要更改中序遍历的遍历方式,改为 右→根→左。 这样遍历的序列就是递减排序的
        /*private void getKthNode(TreeNode node, int k){
            if (ans == null){ // 剪枝操作,ans为空时说明还没找到第k个节点,如果找到了就没必要遍历其他节点了
                if (node.right != null)
                    getKthNode(node.right,k);
                if (index == k){
                    ans = node;
                }
                index++;
                if (node.left != null)
                    getKthNode(node.left,k);
            }
        }*/
    }
     
  • 相关阅读:
    cgroup开机自启动
    QPS
    Linux shell脚本的字符串截取
    设计模式 java
    kafka基本介绍
    Vagrant安装配置
    SuperMap空间数据处理与制图操作短视频汇总
    SuperMap 三维产品资料一览表
    SuperMap GIS资料-----云与Web端技术资料集锦
    世界地图和主要国家的 JSON 文件
  • 原文地址:https://www.cnblogs.com/HuangYJ/p/13637531.html
Copyright © 2020-2023  润新知