zoukankan      html  css  js  c++  java
  • 二叉搜索树的第 k 个结点


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


    解题思路

    根据二叉搜索树的性质,按照中序遍历的顺序打印出来正好就是排序好的顺序,所以,按照中序遍历顺序找到第 k个结点就是结果

    在遍历过程中,如果发现有符合条件的结点,则直接递归向上返回,因此返回的 node 必然不为空,正好符合判断条件。如果不做 node 是否为 null 的判断,则目标结点会被其父结点所覆盖

    public class Solution {
        
        int count = 1;
        TreeNode KthNode(TreeNode pRoot, int k) {
            if(pRoot != null) {
                TreeNode node = KthNode(pRoot.left, k);
                if(node != null) {
                    return node;
                }
                if(count == k) {
                    return pRoot;
                }
                count++;
                node = KthNode(pRoot.right, k);
                if(node != null) {
                    return node;
                }
            }
            return null;
        }
    }
    

  • 相关阅读:
    [栈]
    [数据结构实验]学生成绩管理
    [数据结构实验]集合交并
    shapefile 转 geojson 文件类型
    ubuntu sublime text key
    opengl
    c++
    sublime text3 key
    ubuntu安装nvidia驱动
    全球国家svg边界svg
  • 原文地址:https://www.cnblogs.com/Yee-Q/p/14204524.html
Copyright © 2011-2022 走看看