zoukankan      html  css  js  c++  java
  • 剑指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);
            }
        }*/
    }
     
  • 相关阅读:
    软件工程课堂练习-最高折扣
    小组开发项目NABC分析
    《梦断代码》阅读笔记二
    软件工程课堂练习--结对开发
    软件工程课堂练习--结对开发
    结对开发四
    电梯调度需求分析
    软件工程课堂练习——结队开发二
    电梯调度——课堂练习
    团队项目开发——用户需求调研报告
  • 原文地址:https://www.cnblogs.com/HuangYJ/p/13637531.html
Copyright © 2011-2022 走看看