zoukankan      html  css  js  c++  java
  • 剑指Offer对答如流系列

    面试题54:二叉搜索树的第k个结点

    题目描述

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

    例如,图中的二叉搜索树,按节点值大小顺序,第三大节点的值是4.
    在这里插入图片描述

    二叉搜索树的节点定义

    	public class Node {
            int val = 0;
            Node left = null;
            Node right = null;
    
            public Node(int val) {
                this.val = val;
            }
        }
    

    问题分析

    二叉搜索树中序遍历的结果是顺序的。我们可以设置一个全局变量index,对二叉搜索树进行中序遍历时,每遍历一个结点,index++,当index=k时,该结点即为所求结点。

    问题解答

    	private int index=0;
    
        Node KthNode(Node pRoot, int k){
            Node pNode = null;
            if(pRoot==null || k<=0) {
                return pNode;
            }
            pNode = getKthNode(pRoot,k);
            return pNode;
        }
    
        private Node getKthNode(Node pRoot, int k){
            Node kthNode=null;
    
            if(pRoot.left!=null) {
                kthNode=getKthNode(pRoot.left,k);
            }
            
            if(kthNode==null){
                index++;
                if(k==index) {
                    kthNode = pRoot;
                }
            }
    
            if(kthNode==null && pRoot.right!=null) {
                kthNode=getKthNode(pRoot.right,k);
            }
            
            return kthNode;
        }
    
  • 相关阅读:
    本学期的学习计划
    snmp 学习记录
    解锁树莓派root账号
    树莓派通过阿里云内网穿透,搭建下载机
    golang Ordered Map
    go 切片slice奇怪的地方
    学习scons总结
    go语言学习小结
    学习git版本管理工具
    轻松记账工程冲刺第二阶段10
  • 原文地址:https://www.cnblogs.com/JefferyChenXiao/p/12246768.html
Copyright © 2011-2022 走看看