博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode]230. Kth Smallest Element in a BST
阅读量:2786 次
发布时间:2019-05-13

本文共 1677 字,大约阅读时间需要 5 分钟。

找出BST中的第k个节点值

BST的中序遍历就是一个升序数组啊!!!!

数左子树中节点个数num,如果是k - 1个,那么当前root即为所求;如果num大于k,则从左子树中找第k个;否则从右子树中找第k - 1 - num个(即减去左子树中节点个数以及root这一个)

public class Solution {    public int kthSmallest(TreeNode root, int k) {        int num = count(root.left);        if (num >= k) {            return kthSmallest(root.left, k);        } else if (num + 1 < k) {            // 注意第二个参数            return kthSmallest(root.right, k - 1 - num);        }        return root.val;    }    private int count(TreeNode root) {        if (root == null) {            return 0;        }        return 1 + count(root.left) + count(root.right);    }}

注意dfs的时候函数调用的时候就要保证root不是null,这样里面就不用判断了

递归二叉树的中序遍历

public class Solution {    int count = 0;    int num = 0;    public int kthSmallest(TreeNode root, int k) {        count = k;        dfs(root);        return num;    }    private void dfs(TreeNode root) {        if (root.left != null) {            dfs(root.left);        }        count--;        if (count == 0) {            num = root.val;            return;        }        if (root.right != null) {            dfs(root.right);        }    }}

非递归二叉树的中序遍历

public class Solution {    public int kthSmallest(TreeNode root, int k) {        Stack
stack = new Stack(); TreeNode cur = root; while (cur != null || !stack.isEmpty()) { while (cur != null) { stack.push(cur); cur = cur.left; } if (!stack.isEmpty()) { cur = stack.pop(); k--; if (k == 0) { return cur.val; } cur = cur.right; } } return -1; }}

转载地址:http://rahld.baihongyu.com/

你可能感兴趣的文章
Maven简介(一)——Maven的安装和settings.xml的配置
查看>>
使用Maven
查看>>
profile介绍
查看>>
Maven仓库介绍
查看>>
Maven的pom.xml介绍
查看>>
Dependency介绍
查看>>
Maven整合Eclipse
查看>>
setting.xml详解
查看>>
maven设置------setting.xml文件学习
查看>>
Maven仓库—Nexus环境搭建及简单介绍
查看>>
Web 通信 之 长连接、长轮询(long polling)
查看>>
Spring中使用Map、Set、List、数组、属性集合的注入方法配置文件
查看>>
apache-shiro杂记(二) 关于多realm认证的策略
查看>>
DelegatingFilterProxy
查看>>
forward和redirect的区别
查看>>
Spring+EhCache缓存实例(详细讲解+源码下载)
查看>>
mysql while,loop,repeat循环,符合条件跳出循环
查看>>
mysql存储过程详解
查看>>
mysql存储过程 游标 循环使用介绍
查看>>
MySql中游标的定义与使用方式
查看>>